Express.js and Sequelize (for MYSQL)

the secret of the config file for sequelize if you are using dotenv

Posted on May 6, 2017 in computer

I am learning how to set up a node server with express routing, and mysql for the database. (Am I leaving laravel?!?)

Everything was running smoothly until I started to set up the database configuration. I do not want the sensitive info like passwords, etc in my version control … that stuff is secret you know. So I installed npm dotenv, and tested how to work it. It seemed simple enough, using the process.env.yourVariableName.

The problem cane when I set up sequelize. I used the cli, and that very nicely set things up for me. It set up a config.json in a config directory. But the json format could not use the process.env.yourVariableName. I did a lot of rooting around and trying the different suggestions that I found.

Finally, I found a good suggestion on their site near the bottom. after combing the docs, I found you could use a config.json file or alternatively a config.js file. The cli automatically installs the config.json. I removed it and used config.js in this format:

    const dotenv = require('dotenv').config();

module.exports = {
  development: {
    database: process.env.DB_NAME,
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    dialect: 'mysql',
  },
}

And having set up my dotenv variables correspondingly, the whole thing jus tmgically worked!!

Now I feel so safe about using it all. And in fact, the sequelize documents were, while not the best ever, quite good and easy enough to use when you become a bit more familiar with them. I rather feel confortable now after about twenty minutes getting warmed up to their docs.