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


Question

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.

1
81
5/31/2012 7:49:23 AM

Accepted Answer

You can set your environment variables in process.env:

process.env['VARIABLE'] = 'value';

Node should take care of the platform specifics.

123
5/31/2012 8:22:15 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon