0👍
I like to create a .env file in the root of my project which could look like this:
DB_USERNAME=user
DB_PASSWORD=paszw0rd
DB_HOST=127.0.0.1
Then you can use dotenv to access these values easily
npm install dotenv
require('dotenv').config();
console.log(process.env.DB_HOST); // 127.0.0.1
Then you can simply have a different .env file on your server and on your machine. I add the .env file to my .gitignore as it usually contains secrets and instead add a .env.example file with the available keys.
The benefit of this method is that you don’t have to make any changes to your code to accomodate different environments, you just need to provide a .env file with all the necessary variables.
You can also supply these variables as environment variables, e.g. when you start the script:
DB_PASSWORD=secret node server.js
Or inside a pm2 ecosystem file or whatever method you prefer. You can still access them via "process.env" afterwards.