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:
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?
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 :)
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');
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.
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); ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With