How to handle multiples environments (dev/prod) in one nodejs app?

232 views Asked by At

I'm not sure if it is possible to do something like this.

I have two Reactjs project p1 and p2. For the server, I'm using Loopback3 and MongoDB. Both projects will connect to one server.

What I want is to create multiple host database in one server so if I login to p1 project, it will use p1 database. If I login to p2 project, it will use p2 database.

Each p1 and p2 will have it own environment for development and production

I have the NODE_ENV to check for p1 and I can separate the development and production. I use the same method to create datesource.p2.json and server.p2.js, but I cannot change the NODE_ENV to use p2 database.

Here is the script in package.json

  "scripts": {
    "heroku-prebuild": "npm install",
    "start-P2": "node ./server/server.p2.js",
    "start": "node ./server/server.p1.js",
    "posttest": "npm run lint && nsp check",
    "devserver": "nodemon ./server/server.js"
  },
1

There are 1 answers

1
chill389cc On

As long as you are on a unix-based system, you can do something like this in your script:

"scripts": {
    ...
    "start-P2": "env_name=p2 node ./server/server.p2.js",
    "start": "env_name=p1 node ./server/server.p1.js",
    ...
  },

where env_name is the name of the environment variable that you will use to detect which environment to connect to. Then in your code just check whether that variable equals p1 or p2 (or something else).