Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js on Heroku: PostgreSQL on prod, SQLite3 on dev?

Node.js on Heroku: PostgreSQL on prod, SQLite3 on dev?


I have a Node.js/Rails3 app that I'm hosting on Heroku. The rails portion seamlessly switches between PostgreSQL and SQLite3 when it's run on my local machine or the remote production box.

Locally, the rails framework connects to SQLite3 as defined in config/databases.yml and when I push to Heorku, the deploy scripts overwrite this with their production setup.

My node.js scripts don't have a framework that Heroku can hook into and make sure I'm using the right database in my production environment.

How can I make my node.js scripts "Just Work" the way my Rails app moves seamlessly between development and production environments?

Problem courtesy of: Jordan Feldstein


Heroku exposes a database URL you can connect to via the DATABASE_URL environment variable. Here's the relevant section from the Heroku Dev Center docs.

Using a Postgres Database

To add a PostgreSQL database to your app, run this command:

$ heroku addons:add shared-database

This sets the DATABASE_URL environment variable. Add the postgres NPM module to your dependencies:

"dependencies": {
  "pg": "0.5.4"

And use the module to connect to DATABASE_URL from somewhere in your code:

var pg = require('pg');

pg.connect(process.env.DATABASE_URL, function(err, client) {
  var query = client.query('SELECT * FROM your_table');

  query.on('row', function(row) {
Solution courtesy of: Michelle Tilley


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js on Heroku: PostgreSQL on prod, SQLite3 on dev?


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription