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     : '',
              user     : 'username',
              password : 'password',
              database : 'databaseName'

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.

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


    Then you can access them like:

    var connection = mysql.createConnection({
              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


    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

    Then from your code

    let host =;

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