Search code examples
javascriptenvironment-variablessequelize.jsnestjs

How to use env in Sequelize migration config file?


I use NestJS. At the root of the project I created a file .sequelizerc:

const path = require('path');

module.exports = {
  'seeders-path': path.resolve('src/database', 'seeders'),
  'migrations-path': path.resolve('src/database', 'migrations'),
  config: path.resolve('src/database', 'config.js'),
};

As well as the configuration file in src/database/config.js:

module.exports = {
  development: {
    dialect: 'mysql',
    host: process.env.DB_HOST,
    port: Number(process.env.DB_HOST),
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
  },
  production: {
    dialect: 'mysql',
    host: process.env.DB_HOST,
    port: Number(process.env.DB_HOST),
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
  },
};

When running the migration (npx sequelize-cli db:migrate) using env I get the error: Access denied for user ''@'localhost' <using password: NO>. The reason for the error is that it is not possible to read values from env.

How can I use env in given config?

I tried adding require('dotenv').config() to the config.js. But it didn't work.


Solution

  • I solved it. The problem was that I used .development.env and .production.env.

    I added require('dotenv').config({ path: '.production.env' }) to config.js.