SETUP SEQUELIZE ON NODEJS

Izabayo Blaise
2 min readSep 22, 2020

--

This is a follow up to setting up a simple node server with express and babel

ENVIRONMENT VARIABLES IN NODE.JS

It is important to set data like private API keys and user credentials like password, username, and email as environmental variables, but without exposing them in the source code. For this, we put environmental variables in a dedicated file that is safe from external access. The .env file lets you set Node.js environment variables as accessible in your project’s source code. On the command line, in your project’s root folder, create a .env file:

touch .env

Now you can place any key-value pair that you don’t want in your source code in this new file.

MY_SECRET=mysupersecretpassword
PORT=3000

dotenv is another helpful library to make environmental variables accessible in the source code. First, install it on the command line as a normal dependency:

npm install dotenv --save

Second, import it into your src/index.js file to initialize it. The environment variable from your .env file is now accessible in your source code.

import express from "express";
import 'dotenv/config';
const app = express();app.listen(process.env.PORT, () => {
console.log(`Listening on port ${process.env.PORT`);
});

SEQUELIZE SETUP

After doing the setup, you may want to connect to a database. I will use Postgres in my case. Secondly, I choose to do it with Sequelize ORM.

  1. Install Sequelize, Sequelize CLI, pg, and pg-hstore using the command below. To get an explanation, check this link: npm install sequelize pg pg-hstore
  2. Install Sequelize-CLI: npm install sequelize-cli -g
  3. Create a .sequelizerc and add the code below:
const path = require('path')module.exports = {
config: path.resolve('./database/config', 'config.js'),
'models-path': path.resolve('./database/models'),
'seeders-path': path.resolve('./database/seeders'),
'migrations-path': path.resolve('./database/migrations'),
}

4. Generate a config: sequelize init

5. now all we need is to add our database details to the ‘./database/config/config.js’ file. Note: Make sure that you have different databases for different environments, in the end, we should be having something which looks like this

import dotenv from 'dotenv';
dotenv.config();
const config = {
development: {
use_env_variable: 'DATABASE_DEV_URL',
dialect: 'postgresql',
},
test: {
use_env_variable: 'DATABASE_TEST_URL',
dialect: 'postgresql',
logging: false
},
production: {
use_env_variable: 'DATABASE_URL',
dialect: 'postgresql',
logging: false
}
};
module.exports = config;

if the logging: false is confusing you just know it’s put there to make sure that SQL queries aren’t logged in the console log whenever a database operation happens
example of a database URL

DATABASE_DEV_URL=postgres://your_db_user:your_password@127.0.0.1:5432/your_dev_db_name

--

--

No responses yet