How to set environment variable when using 'npm' command in node.js applications?
1. Purpose
In this post, I will demonstrate how to set environment variables for npm
commands, I need to execute the following command to export an environment variable before running npm start
:
Then I would run:
However, it is tedious to execute the export
command every time I start the application. For example:
Is there a way to set this up just once?
Yes, you can achieve this by using cross-env
in your package.json
.
2. The solution
2.1 The answer
TL;DR: The solution is to modify your package.json
file.
Before:
After modification:
The key difference is the addition of a prefix to the original command:
Now, you can start the application with:
With this setup, you no longer need to manually set the NODE_OPTIONS
environment variable each time you start the app. Simply configure it in your package.json
, and you’re done.
2.2 The theory
1) What is cross-env
?
The core module used to resolve this issue is cross-env
. But what exactly is cross-env
?
cross-env allows you to set environment variables in a way that works across different platforms. You can define environment variables as you would on a POSIX system, and cross-env ensures they are set correctly regardless of the platform.
2) How to install cross-env?
You can install cross-env
globally using the following command:
Version 7 of cross-env
only supports Node.js 10 and higher. If you are using Node.js 8 or lower, install version 6:
3) How to use cross-env?
Here are some examples of how to use cross-env
:
You can also set multiple environment variables:
Additionally, you can split a command into multiple lines or separate the environment variables declaration from the actual command execution:
3. Summary
In this post, I demonstrated how to set environment variables for your Node.js applications using the cross-env
tool. This approach eliminates the need to manually export variables each time you run your application. By configuring your package.json
file, you can streamline your development workflow and ensure consistent behavior across different platforms.
Final Words + More Resources
My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!