How to hide connection details for mysql database in node.js?

I just began working with mysql in node.js and I am setting up my app.js project and I am trying to hide my connection details such as my ip, username, pw, and db name. I don't know how to go about hiding my connection details, so this is why i'm here.

I have tried to add the details in my .profile, but I keep getting an authentication error. But, when I include these same connection details in my regular app.js file, it works and connects to the database.

Here is what is being displayed in my app.js file:

var connection = mysql.createConnection({
              host     : 'my.ip.address.info',
              user     : 'username',
              password : 'password',
              database : 'databaseName'
            });
console.log('Connected');
connection.connect();

I just want to hide my connection details so that when my site goes live in the future it is secured from prying eyes. I understand that leaving these connection details in my app.js file is not the correct thing to do, so that's why I'm asking for help! lol

2 answers

  • answered 2019-08-13 03:16 VtoCorleone

    You can create a .env file to set environment variables and use the dotenv package to surface them in your process.env.

    https://github.com/motdotla/dotenv#readme

    Create a file and name it .env and set your variables as such

    host=my-ip-address-info,
    user=username,
    password=password,
    database=databaseName
    

    Then you can access them like:

    var connection = mysql.createConnection({
              host: process.env.host
              user: process.env.username
              password: process.env.password,
              database: process.env.database
            });
    

    You'll have to start your app with something like

    node -r dotenv/config your_script.js

    or add the following to the top of your entry script

    require('dotenv').config();

    I prefer the first method because those environment variables should be set by your host provider so there is no need for the require statement in your code.

  • answered 2019-08-13 03:18 rodrigoap

    I use dotenv.

    yarn add dotenv
    

    Create a .env file in the root directory of your project

    host=my.ip.address.info
    user=username
    password=password
    database=databaseName
    

    Then from your code

    require('dotenv').config();
    
    let host = process.env.host;
    

    Do not commit the .env file to a public repo.