Search code examples
node.jsconfigurationpasswordspassword-protection

How can I securely store the IP address, username and password of a database using Node.js?


I have Node.js code to connect to a MySQL database:

var mysql = require('mysql')
var express = require('express')
var app = express()

var connection = mysql.createPool({
    connectionLimit: 50,
      host     : 'ip',
    user     : 'username',
      password : 'pass',
      database : 'mydb'
});


app.get('/', function(req, resp) {
    connection.getConnection(function(error, tempCont) {
        if(!!error) {
            tempCont.release();
            console.log('Error');
        } else {
            console.log('Connected!');

            tempCont.query("select * from table", function(error, rows, fields) {
                tempCont.release();
                if(!!error) {
                    console.log('Error in the query');
                } else {
                    resp.json(rows);
                }
            });
        }
    })
})

console.log("listening requests...")
app.listen(1337);

How do I secure an IP address, username and password used for connecting to a database so that is not visible in the code or configuration file?


Solution

  • Install the dotenv module by: npm install --save dotenv

    Create a .env file at the root folder and write down the code:

    DB_CONLIMIT=50
    DB_HOST=ip
    DB_USER=username
    DB_PASSWORD=pass
    DB_DATABASE=mydb
    

    In your JavaScript file:

    var mysql = require('mysql');
    var express = require('express');
    var app = express();
    const dotenv = require('dotenv').config();
    
    var connection = mysql.createPool({
    
         connectionLimit : process.env.DB_CONLIMIT,
         host            : process.env.DB_HOST,
         user            : process.env.DB_USER ,
         password        : process.env.DB_PASSWORD ,
         database        : process.env.DB_DATABASE
    });