0

I need a requirement on node js apis. I need to set environment in the url like http://localhost:8000/api/(env)/auth/login, where env can be dev,production.

Now I want to get that value and according to the value I need to set the database connection string (either in environment file or config file).

Requirement is----

dev environment - http://localhost:8000/api/dev/auth/login : in that case the database would be ----- test_dev and all data would be get/stored in that database -- production environment - http://localhost:8000/api/prod/auth/login : in that case the database would be test_prod and all data would be get/strored in prod database

I am confused where to write the code and how to get the environment name? I set the routes as follows ---

**in app.js file - **  app.use("/api/:environment/", apiRouter); //api router is path of api.js

**in api.js file - ** app.use("/auth/", authRouter); //authRouter is path of auth.js

**in auth.js file - ** router.post("/login", AuthController.login);

Please suggest how will I achieve this problem.

Thanks

PHP Geek
  • 3,949
  • 1
  • 16
  • 32

1 Answers1

1

To get the environment name, you could try something like this.

app.param(function (param, option) {   
return function (req, res, next, val) {
    if (val === option) {
      next()
    } else {
      next('route')
    }   } })

app.param('enviornment', env)

app.use(`/api/:enviornment/`,(req, res) => {
    res.send(`<h1>Welcome to ${req.params.enviornment}</h1>`); })

However ^^ this is depreciated.

Ideally, you should use .dotenv based approach rather than having /dev/ or /prod/ endpoints to access API in Dev/Prod mode.

Install dotenv using npm i dotenv or yarn add dotenv.

Create a .env.dev and .env.prod file in your root directory, add your test_dev and test_prod db config string in respective files.

Eg.

/* .env.dev file */
MONGO_URL="xxx.....xxx" // test_dev string
/* .env.prod file */
MONGO_URL="xxx.....xxx" // test_prod string

Now, in your database config file add dotenv as,

require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })

Now, you can access the MONGO_URL by process.env.MONGO_URL

Next, update your scripts in package.json

eg. dev: NODE_ENV=dev nodemon app.js and start: NODE_ENV=prod node app.js

Now, depending on which script you run the API is handled correctly in dev/prod environments.

If you run the dev script, the test_dev DB will be used, etc. (vice versa)

Similarly, you can define and access all your environment variables in this manner.

Further refactoring can be made if you have many environment variables,

Create a config.js file,

require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })

const MONGO_URL = process.env.MONGO_URL
const OAUTH_PROVIDER_ID = process.env.OAUTH_PROVIDER_ID
const OAUTH_PROVIDER_SECRET = process.env.OAUTH_PROVIDER_SECRET
const JWT_SECRET = process.env.JWT_SECRET

export {
 MONGO_URL,
 OAUTH_PROVIDER_ID, 
 OAUTH_PROVIDER_SECRET,
 JWT_SECRET
}

Now, you can destructure and use it wherever required.

Eg. in db.config.js

const { MONGO_URL } = require('./config')
Jagan Kaartik
  • 580
  • 2
  • 7
  • 15
  • This is not what the question asks. It is about how to change the ENV variables in the run time environment – Apoorva Chikara May 26 '21 at 11:07
  • 1
    thanks Jagan Kartik. I agree ideally this should be there, but I need it dynamic from mobile app to access the environment without changing anything on command and code level. there would be 2 or 3 urls. one each for environment. and I just want to access the database according to the value in the url. – PHP Geek May 26 '21 at 11:16
  • Jagan Kartik, the solution working fine, but can you let me know how can we change the db instance at run time? – PHP Geek May 27 '21 at 04:22
  • Please look into these examples [Example 1](https://stackoverflow.com/questions/42780489/sequelize-connect-to-database-on-run-time-based-on-the-request) and [Example 2](https://stackoverflow.com/questions/51134784/how-to-change-db-connection-in-node-js-dynamically) – Jagan Kaartik May 27 '21 at 08:29