0

I found some other similar answers to this, but I was not confident in my ability to comprehend and get it right, so I'm hoping to get a little validation on my approach if it's right, seeing as what i've cobbled together is from a tutorial. I've also included the requires, as I'm not actually calling express in this file (db.js) but it is used in other places:

(PS. I am deploying to Heroku, and using JawsDB as my production DB)

require("dotenv").config();
const mysql = require("mysql2");
//const { DatabaseError } = require('pg');

const pool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    database: process.env.DB_NAME,
    password: process.env.DB_PASSWORD,
});

and this is what i'm thinking of doing:

app.configure('production', function(){
    app.locals.URLs = {
        const pool = mysql.createPool({
             host: process.env.DB_HOST_LOCAL,
             user: process.env.DB_USER_LOCAL,
             database: process.env.DB_NAME_LOCAL,
             password: process.env.DB_PASSWORD_LOCAL,
    }
});
app.configure('development', function(){
    app.locals.URLs = {
        const pool = mysql.createPool({
             host: process.env.DB_HOST_JAWS,
             user: process.env.DB_USER_JAWS,
             database: process.env.DB_NAME_JAWS,
             password: process.env.DB_PASSWORD_JAWS,
    }
});

is this right, and will I need to require app = require('express')?

Sharan Balani
  • 143
  • 1
  • 9

1 Answers1

0

If you want to inject anything into express (router, middleware, configuration, template engine, etc) then you're gonna need "app". With locals you are creating a "URLs" property inside your app instance.

This is not a big deal but you could instead module.exports = pool; as an independent js module and use it regardless of Express.

About your env, be cautious no to leak production passwords into development nor a developer's local configuration into production. That said you don't need a if.. else for your configuration. I also spot you don't have an env configuration for tests...

Here in the docs the prefered way to load your vars is by preloading them.

node -r dotenv/config your_script.js

You can also customize your .env file if you enjoy .env.local .env.production .env.test approach

node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env

This also allows you to have multiple settings without worry of conflicts / unintended overrides or leftovers. You could also

  • inject individual variables via cross-env
  • inject production variables via PM2