Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using an enviroment variable for local sequelize configuration

Tags:

I'm looking to use an environment variable inside of the config.json file of my project using sequelize. I'm using dotenv to set environment variables locally. My config.json file looks like this

{   "development": {     "username": process.env.DB_USER,     "password": process.env.DB_PASS,     "database": process.env.DB_DATABASE,     "host": process.env.DB_HOST,     "dialect": "mysql"   },   "test": {     "username": "root",     "password": null,     "database": "database_test",     "host": "127.0.0.1",     "dialect": "mysql"   },   "production": {     "use_env_variable": "JAWSDB_URL",     "dialect": "mysql"   } } 

The issue I'm having is that I can't use variables inside the config.json file. It looks like for production I can use the "use_env_varable" key and use the env variable for my connection string. So I guess I either need a way to figure out the combined connection string for my local mysql db or a way to use variables inside the config.json. Any solutions?

like image 438
ceckenrode Avatar asked Aug 04 '16 02:08

ceckenrode


2 Answers

you should change config.json file to a config.js module and make sure to require the dotenv at the very top.

require('dotenv').config(); // this is important! module.exports = { "development": {     "username": process.env.DB_USERNAME,     "password": process.env.DB_PASSWORD,     "database": process.env.DB_DATABASE,     "host": process.env.DB_HOST,     "dialect": "mysql" }, "test": {     "username": "root",     "password": null,     "database": "database_test",     "host": "127.0.0.1",     "dialect": "mysql" }, "production": {     "username": "root",     "password": null,     "database": "database_production",     "host": "127.0.0.1",     "dialect": "mysql" } }; 

NOTE: update your .sequelizerc file to match the new config file.

"config": path.resolve('./config', 'config.js'), 
like image 112
Ali Sherafat Avatar answered Sep 20 '22 11:09

Ali Sherafat


I worked on this for quite a bit. I do not know why Sequelize does not use production when it is literally in the environment if you run heroku run bash. I was able to get it working by modifying the Sequelize object depending on the JAWSDB_URL, not the NODE_ENV.

require("dotenv").config(); const express = require("express") const app = express(); let seq;  //express app configuration  if (process.env.JAWSDB_URL) {     console.log("There is a JAWS DB URL")     seq = new Sequelize(process.env.JAWSDB_URL) } else {     seq = require("./models").sequelize } seq.sync().then(() => {   app.listen(PORT, () => console.log('server started on port ' + PORT)); }) 
like image 33
Justin Rice Avatar answered Sep 18 '22 11:09

Justin Rice