128

How can I set an environmental variable in node.js?

I would prefer not to rely on anything platform specific, such as running export or cmd.exe's set.

abrkn
  • 1,971
  • 2
  • 15
  • 16

4 Answers4

193

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.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
lanzz
  • 42,060
  • 10
  • 89
  • 98
  • 4
    I don't think you need to do `var process = require('process')`, process is a global variable present. – alessioalex May 31 '12 at 08:18
  • 113
    Note, though, that this will only set the variable within your node process and any child processes it calls; it will not, for example, leave the variable set in the shell when the node process exits (changing the environment of a parent process is very system-dependent and not always even possible). – ebohlman May 31 '12 at 20:09
  • 2
    anyone offer an opinion on process.env.variable vs global.variable? – Scott Silvi Jul 25 '14 at 02:50
  • Why not use `process.env.VARIABLE`? – Luca Steeb Jan 26 '15 at 13:21
  • 6
    `process.env.VARIABLE` is okay if the variable name is a known constant, while `process.env['VARIABLE']` works in any case; original question did not specify enough detail, so the more versatile example seemed better suited. – lanzz Jan 26 '15 at 17:20
  • @ebohlman Is it possible to leave the variable set in the shell after the node process finishes? – Bill Morris Aug 10 '15 at 02:51
  • 3
    @BillMorris no, it is not possible for any process to modify its parent's environment – lanzz Aug 10 '15 at 06:44
  • You should be able to write to the current users .profile or .bashrc then source it, if you do want to manipulate the parent environment – Eric Uldall Jun 14 '16 at 00:53
  • @EricUldall no, .profile and .bashrc are loaded when a shell starts; they will not be automatically re-executed by an already running shell, and then again the parent process might not be a shell at all. – lanzz Jun 14 '16 at 06:57
  • @lanzz, that is correct. I think you misinterpreted my solution though. `source $(node-exec); #adds export to profile and prints filename to stdout` – Eric Uldall Jun 14 '16 at 18:22
  • can we use this variable while executing some of our python scripts without passing it as a command line argument? – Prabhat Mishra Jun 01 '18 at 10:44
  • @user9645113 yes, that's exactly how environment variables work. You can access them in your scripts via the `os.environ` dictionary – lanzz Jun 02 '18 at 16:53
  • yeah but i am unable to do so getting error defined this in my node-app `process.env.data = "data-env";` and now i am unable to access this variable in python script using this `print(os.environ["data"])` can you tell me what's going wrong with this @lanzz? – Prabhat Mishra Jun 03 '18 at 18:46
  • @user9645113 you should open a new question with a full description of your circumstances. Comments aren't the right venue for solving your problem – lanzz Jun 03 '18 at 19:30
  • By some reason this approach doesn't work and throws an error: `ReferenceError: Left side of assignment is not a reference.` What might be wrong? – orkenstein Jun 27 '19 at 16:34
4

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.

Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
jagjeet
  • 376
  • 4
  • 12
  • 2
    How secure is the .env file used by dotenv? If the secrets are plain text within environment strings in the .env file, is that any more secure than having them as plain text in your node code? Which is clearly a no-no? – Ric Mar 22 '20 at 23:25
  • The OP is asking how to set an environment variable from within a nodejs process/script, and not to read from a .env file and use it during runtime. – cezarlamann Oct 10 '22 at 23:34
1

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
Rafiq
  • 8,987
  • 4
  • 35
  • 35
  • The OP is asking how to set an environment variable from within a nodejs process/script, and not to read from a .env file and use it during runtime. – cezarlamann Oct 10 '22 at 23:35
0

Well what I do is I first install dotenv package from npm

npm install dotenv

Then I import it in my file.

require('dotenv').config();

Then You are good to go. :)

You can read variables by using:

console.log(process.env.MY_VARIABLE);

While you can SET a Variable by using:

process.env.MY_OTHER_VARIABLE = 'helloworld;

J.F.
  • 13,927
  • 9
  • 27
  • 65
spadletskys
  • 125
  • 7