Skip to content

Instantly share code, notes, and snippets.

@agmezr
Last active June 27, 2018 05:14
Show Gist options
  • Save agmezr/b68c8495987e7ee9c20c51b4ecdb9d84 to your computer and use it in GitHub Desktop.
Save agmezr/b68c8495987e7ee9c20c51b4ecdb9d84 to your computer and use it in GitHub Desktop.
An example of a server configuration for using node and postgres on heroku
// Since It's not a good idea to have everything on the server.js I moved the pool creation to this file
// Require the pg module
const { Pool } = require('pg');
// You can either do this or check if we are in production like in server.js
// In this case if the DATABASE_URL is declared we use it to the connection
const { DATABASE_URL } = process.env;
if (DATABASE_URL){
console.log("Using database url");
var pool = new Pool({
connectionString: DATABASE_URL
});
}else{
// if the database url is not set use a local database for dev.
console.log("Using database info");
var pool = new Pool({
user: '<USER>',
host: 'localhost',
database: '<DATABASE_NAME>',
password: '<DATABASE_PASSWORD>',
port: 5432 // default port for postgres
});
}
module.exports = pool;
// To use this pool on another file, use something like this:
// const pool = require('path/to/file/database');
// A simple example to run node in heroku
//I use helmet to secure headers on production
// see https://www.npmjs.com/package/helmet for more info
const helmet = require('helmet'),
{ Pool } = require('pg');
// ...
// Your other require or config
// When deploying, heroku will set the env port to whatever port is use, if you set it static your app will not run
const PORT = process.env.PORT || 8080;
// By default heroku will set NODE_ENV to production, I stored it in a variable to set various configuration
// like pg and helmet
const PROD = process.env.NODE_ENV === "production" || false;
// If in production this will be true
if (PROD){
// Apply helmet
app.use(helmet());
console.log("Added helmet headers");
// An example of connecting with the postgres db on heroku
// You can obtain the url of your database with the following command:
// heroku pg:credentials:url DATABASE
// then create a new config var DATABASE_URL in the Settings tab on heroku and paste the url.
// For an example of how to create the pool in another file, see database.js
const { DATABASE_URL } = process.env;
var pool = new Pool({
connectionString: DATABASE_URL
});
}else{
// Set stuff you use in dev like logs
}
// Your routes and other stuff
app.listen(PORT);
console.log(`Staring app on ${PORT}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment