Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hardcoded mysql user and password in Node.js

Tags:

node.js

mysql

I'm using mysql with node.js. Something like this:

    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'me',
      password : 'secret',
      database : 'my_db'
    });

    connection.connect();

I was just wondering if having the database credentials (user and password) hardcoded in the server doesn't compromise security. If it does, what would be a better way of doing this?

like image 308
gfields Avatar asked Aug 25 '15 17:08

gfields


1 Answers

The best way to handle this is to have your credentials stored in environment variables. You would then access your credentials like this:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : process.env.DB_HOST,
  user     : process.env.DB_USER,
  password : process.env.DB_PASS,
  database : process.env.DB_NAME
});

connection.connect();

Then you would use a library like dotenv to set environment variables. You would put your environment variables in a .env file that is not distributed with the application, and that isn't in version control. An example .env might look like this

DB_NAME=my_db
DB_HOST=localhost
DB_PASS=secret
DB_USER=me

https://www.npmjs.com/package/dotenv - see this link for more information on using dotenv and do some research on 12 factor security in apps :)

like image 105
Brad Decker Avatar answered Nov 06 '22 21:11

Brad Decker