How to use Environmental Variables in NodeJS
📣 Sponsor
Environment variables are a quick and easy way to set up variables which may change from server to server, or from local machine to production server.
A classic example, is checking whether you are on the production server or not. You might then use HTTPS on your production server, but not on your local development machine.
Using Environmental Variables with NodeJS
NodeJS doesn't have an easily built in environmental capability, but fortunately there is an npm package which can help with that. To install it, run this command:
npm i dotenv
Now we have that installed, lets include it in the top of our Node.JS file:
import dotenv from 'dotenv';
dotenv.config();
Or with require..
// Or..
const dotenv = require('dotenv');
dotenv.config();
Great, now all we have to do is create a file in our base directory called .env
. Inside it, we can put our variables in this format:
environment=production
serverid=000001
Then, in our Javascript, when we want to refer to a specific variable, we do it like this:
console.log(process.env.environment); // Returns production
console.log(process.env.serverid); // Returns 000001
Easy, right? And if we want to change the location of our .env
file, we can update that in the config at the top of the page:
import dotenv from 'dotenv'
dotenv.config({ path: './path/to/new/.env' });
More Tips and Tricks for Javascript
- Javascript Shallow Copies - what is a Shallow Copy?
- A Look at the New Array Methods coming to Javascript
- A Guide to Heaps, Stacks, References and Values in Javascript
- Truthy and Falsy Values in Javascript
- Javascript loops: for vs forEach vs for.. in vs for.. of
- Art Generator with Javascript and WebGL
- How to Auto Generate Images with Node.JS and Canvas
- Javascript Reserved Keywords
- Making a Morphing 3D Sphere in Javascript with Three.js
- Javascript Ordinals: Adding st, nd, rd and th suffixes to a number