138

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

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

1

4 Answers 4

208

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.

Sign up to request clarification or add additional context in comments.

20 Comments

I don't think you need to do var process = require('process'), process is a global variable present.
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).
anyone offer an opinion on process.env.variable vs global.variable?
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.
@BillMorris no, it is not possible for any process to modify its parent's environment
|
3

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.

3 Comments

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?
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.
"set an environment variable in node.js" does not necessarily mean "from within node.js", but could mean "in the ecosystem of node.js". I found this on a search for the latter, and this is the answer I am looking for
0

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

1 Comment

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.
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;

2 Comments

Please do not use headers in your reply.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.