Search code examples
node.jspostgresqlexpressheroku

How to connect to Heroku PostgresQL database from Express?


I am trying to deploy a PERN app to Heroku. I created a Heroku Postgres database and deployed my React frontend - Node/Express backend app to Heroku.

How do I connect to the database from within my Express code? I have been using npm pg so far when the app was still local.

I can't seem to find any information about this on the internet...


Solution

  • You'll need to import a Pool from the postgre module, then set the connection string. It should look something like this:

    const {Pool} = require('pg');
    
    const connectStr = process.env.DATABASE_URL;
    const pool = new Pool({
        connectionString: connectStr,
        ssl: true
    });
    

    Then you can query the database with something akin to this:

    exports.dbAction = function(req, res) {
    
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
    
    pool.query("select * from exampleTable", (err, 
    results) => {
            if (err) {
                console.log(err);
                throw err;
            }
        res.json(results.rows);
        });
      
    }
    

    process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; instructs Node to allow untrusted certificates (untrusted = not verified by a certificate authority). It's not a recommended setting in production mode. However, while in development, it's a handy workaround.