A Node package for managing environment variables on Windows/Mac/Linux

NicolasBrondinBernard

Author
@NicolasBrondinBernard

If you're having trouble standardizing the management of environment variables across your commands, there's a solution!

Article published on 22/07/2021, last updated on 10/08/2026

If you contribute to a project where developers work on different OSes, you've probably run into problems managing environment variables.

But why not just use a package like dotenv for example?

Because it's not always possible! For example, when you call a build tool (like webpack) and you need to pass it an environment variable, you're not going to change the tool's code to include dotenv.

That's where the following tool can prove very handy, especially for devs working on Windows, where the syntax for environment variables changes between cmd and Powershell...

cross-env

Here's a NodeJS package that will let you solve this problem, and it's very simple to use:

$ npm install cross-env --save

Then, all you need to do is invoke cross-env, initialize all the environment variables you want and call the rest of your usual command. Example:

$ cross-env  NODE_ENV=production node index.js

You'll notice that we don't chain commands here (like with &&), because it's actually cross-env that will "internalize" the execution of your command by creating a new process with spawn.

An article on how spawn works is available on the blog for those interested!

If you need to run a command made up of several subcommands, or to directly use the value of your environment variables (outside of Node), you'll need to use cross-env-shell instead:

$ cross-env-shell   NODE_ENV=production "node index.js && echo $NODE_ENV"

If you're looking for more information, I invite you to check out the documentation directly on NPM: https://www.npmjs.com/package/cross-env


Mildlee sur Unsplash

Finished reading this article?
Our complete courses
Take it to the next level with our courses!

Complete courses, exercises and certificates to really learn programming!

4.8 average rating

Comments (0)

to leave a comment

No comments yet