6
3

More than 3 years have passed since last update.

【Node.js】SequelizeのDB接続情報を環境変数で管理する

Posted at

経緯

Sequelizeのデフォルトは config.json というファイル内でDBへの接続情報を管理しているので、 .env などの環境変数で管理したかった。

結論

config/config.json の中身を以下のようにモジュール化して、拡張子を .js に変更する。

dotenv で環境変数を読み込む。

config.js
require('dotenv').config();

module.exports = {
  'development': {
    'username': process.env.DB_USERNAME,
    'password': process.env.DB_PASS,
    'database': process.env.DB_DATABASE,
    'host': process.env.DB_HOST,
    'port': '3306',
    'dialect': 'mysql',
    'operatorsAliases': false,
  },
};

model/index.js の以下を編集を編集する。

index.js
// 編集前
const config = require(__dirname + '/../config/config.json')[env];
// 編集後
const config = require(__dirname + '/../config/config.js')[env];
6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3