Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to store DB config in Node.Js / Express app

What would be the best way to store DB config (username, password) in an open source app that runs on node.js / Express? Two specific questions:

  1. Shall I put it into a separate config.js file in /lib folder, for example, and never include it into the master repository that is publicly available on GitHub?

  2. To inlcude the config, is it as simple as require('./config.js') from the file that needs it or is there a better way of doing it?

PS sorry if the questions seem a bit simple or not so well formulated, but I'm just starting :)

like image 236
Aerodynamika Avatar asked Mar 12 '14 10:03

Aerodynamika


People also ask

How do I add a node JS config file?

If you prefer to use JavaScript, you can add it to your server file before calling the configuration library, as shown below: js const express = require('express'); process. env. NODE_CONFIG = '{"server": {"host":"localhost", "port":"3030"}}'; const config = require('config');

Why should you separate express APP and server in NodeJS?

Faster testing execution. Getting wider coverage metrics of the code. Allows deploying the same API under flexible and different network conditions. Better separation of concerns and cleaner code.


2 Answers

Here's how I do it:

Create a config.js which contains objects representing your configs:

var config = { development: {     //url to be used in link generation     url: 'http://my.site.com',     //mongodb connection settings     database: {         host:   '127.0.0.1',         port:   '27017',         db:     'site_dev'     },     //server details     server: {         host: '127.0.0.1',         port: '3422'     } }, production: {     //url to be used in link generation     url: 'http://my.site.com',     //mongodb connection settings     database: {         host: '127.0.0.1',         port: '27017',         db:     'site'     },     //server details     server: {         host:   '127.0.0.1',         port:   '3421'     } } }; module.exports = config; 

Then in my index.js (or wherever really),

var env = process.env.NODE_ENV || 'development'; var config = require('./config')[env]; 

Then process with that object, e.g.

var server = express(); server.listen(config.server.port); ... 
like image 193
Stephen Wright Avatar answered Sep 27 '22 19:09

Stephen Wright


For running toy apps where I need to hide db credentials, I use the dotenv module.

Place your sensitive info in a .env file (which is .gitignored), place require('dotenv').config(); in your app; dotenv creates entries in process.env that you can refer to.

.env file:

DATABASE_PASSWORD=mypw DATABASE_NAME=some_db 

To refer to the values:

process.env.DATABASE_PASSWORD 
like image 25
Robb Broome Avatar answered Sep 27 '22 19:09

Robb Broome