How can I set an environmental variable in node.js?
You can set your environment variables in process.env
:
process.env['VARIABLE'] = 'value';
-OR-
process.env.VARIABLE = 'value';
Node should take care of the platform specifics.
node v14.2.0 To set env variable first create a file name config.env in your project home directory and then write all the variables you need, for example
config.env
NODE_ENV=development
PORT=3000
DATABASE=mongodb+srv://lord:<PASSWORD>@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority
DATABASE_LOCAL=mongodb://localhost:27017/tours-test
DATABASE_PASSWORD=UDJUKXJSSJPWMxw
now install dotenv from npm, dotenv will offload your work
npm i dotenv
now in your server starter script, in my case it is server.js use doenv to load env variables.
const dotenv = require('dotenv');
dotenv.config({ path: './config.env' });
const app = require('./app'); // must be after loading env vars using dotenv
//starting server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`app running on port ${port}...`);
});
I am using express, all my express code in app.js, writing here for your reference
const express = require('express');
const tourRouter = require('./route/tourRouter');
const userRouter = require('./route/userRouter');
if (process.env.NODE_ENV === 'development') {
console.log('mode development');
}
app.use(express.json());
app.use('/api/v1/tours', tourRouter);
app.use('/api/v1/users', userRouter);
module.exports = app;
now start your server using the console, I am using nodemon, you can install it from npm;
nodemon server.js
First you should install this package :-
https://github.com/motdotla/dotenv [npm install dotenv
]
Then you need to create a .env file in your project's root directory, and there you can add variables like below:-
NODE_ENV=PRODUCTION
DATABASE_HOST=localhost
Now you can easily access these variables in your code like below:-
require('dotenv').config()
console.log(process.env.NODE_ENV);
It worked for me, hopefully that helps.