Search code examples
node.jsherokuheroku-postgresnode-postgres

How to handle the postgres connection when heroku changes the DATABASE_URL


On Heroku Postgres there is written:

The value of your app’s DATABASE_URL config var might change at any time. You should not rely on this value either inside or outside your Heroku app.

I'm developing a Node.js server that uses node-postgres to connect and manage the connection pool with the database.

But what happens when Heroku changes the DATABASE_URL? How should this problem be managed?


Solution

  • You handle this by always connecting to Postgres using whatever value DATABASE_URL has. For example, you can use this value as a connection string when you create your pool:

    const connectionString = process.env.DATABASE_URL
    
    const pool = new Pool({
      connectionString: connectionString,
    })
    

    Heroku's dynos restart when their environment variables or addons are changed, which should cause your code to pick up the new database connection string when it starts back up.