Becky Siegel
Becky Siegel

Reputation: 91

Node/Express app-- how to change connection string (node-postgress) based on localhost vs. remote server

I have a node application running an express server that is deployed on heroku. I'm using a postgres database (node-postgres) and currently have the application configured with a connection string for the remote database.

I created a local version of the database, and I would like to configure the application to use a different connection string when running the app on localhost.

I need to somehow detect what server I'm on and then put the conString in an if/else kind of statement. Any ideas or examples? I was having trouble finding the right solution.

Upvotes: 3

Views: 1517

Answers (2)

frankpinto
frankpinto

Reputation: 166

I would recommend konfig. Create a file named database.js in a folder named config, include it from your app and konfig does the environment switching.

Example

config/database.json:

{
  "development": {
    "postgresql": {
      "connection_string": "postgres://user:pass@localhost/development"
    }
  },
  "production": {
    "postgresql": {
      "connection_string": "postgres://user:[email protected]/sdfk23jf"
    }
  }
}

app.js:

...
var config = require('konfig')().database.connection_string;
...

Use NODE_ENV when you run the server on the command-line, i.e.

NODE_ENV=production node app.js

and konfig will automatically do the switching, I think it uses "development" by default.

Upvotes: 1

vitaly-t
vitaly-t

Reputation: 25900

For that you should use the standard NodeJS environment variable - NODE_ENV.

It should be set to development on your local machine. And on your production server it is usually defaulted to production, as it is on Heroku: NODE_ENV=production

Then you can access it from your app via process.env.NODE_ENV. This will tell you in which environment your app is running, and thus which of the two connections you should use.

Upvotes: 3

Related Questions