Trying to connect my node.js to Heroku PostgreSQL database. Following Heroku Postgres tutorial

It's Heroku's problem. The "process.env.DATABASE_URL" variable they tell you to use in pg.connect is not functioning.

A simple

console.log(process.env.DATABASE_URL);

Will show that this variable is undefined.

Until Heroku offers a fix, you can hard-code the connection URL as the first argument to pg.connect().

To find your credentials, you can go to your app's PostgreSQL add-on connection settings through http://heroku.com.

The new pg.connect method will look like

var connectionString = "postgres://*USERNAME*:*PASSWORD*@*HOST*:*PORT*/*DATABASE*"

pg.connect(connectionString, function(err, client, done) {
   client.query('SELECT * FROM your_table', function(err, result) {
      done();
      if(err) return console.error(err);
      console.log(result.rows);
   });
});

If the above answers fall a little short for anyone (they did for me) - try appending ?ssl=true to the end of your DATABASE_URL environment variable. Credit to the author of this answer. Best of luck.


You can use: heroku pg:info command to list all your databases. There you will find the exact databse url that you can use in your app - it should be something like that: HEROKU_POSTGRESQL_DBNAME_URL. This url can be used in node.js application:

pg.connect(process.env.HEROKU_POSTGRESQL_DBNAME_URL, function(err, client, done) {
   client.query('SELECT * FROM your_table', function(err, result) {
      done();
      if(err) return console.error(err);
      console.log(result.rows);
   });
});