I am trying to deploy a Node.js application locally on Windows for testing, but I can't seem to set the environment to production. When I run NODE_ENV=production node app.js, I get an error that the command is not recognized. I’ve tried using the GUI environment variables, but the app still defaults to development. Is there a specific command-line syntax for PowerShell or CMD, or should I be using a package like cross-env to make this work across different operating systems?
3 answers
On Windows, the syntax for setting environment variables depends entirely on the terminal you are using. If you are using Command Prompt (CMD), you must use the set command: set NODE_ENV=production&&node app.js. Note the lack of spaces around the && to prevent trailing spaces in the variable name. For PowerShell, the syntax changes to $env:NODE_ENV="production"; node app.js. However, for a professional setup, I highly recommend using the cross-env npm package. By running npm install cross-env and updating your package.json scripts to cross-env NODE_ENV=production node app.js, your command will work seamlessly on Windows, macOS, and Linux without needing terminal-specific logic.
If I set the variable using the set command in CMD, does that variable persist after I close the terminal window, or do I need to re-enter it every time I start a new development session?
The easiest way for modern teams is definitely the cross-env package. It removes all the "Windows vs Linux" headache from your scripts section in package.json.
I agree with Jessica. I spent way too much time debugging why my production builds were failing on our Windows build agent until I realized the PowerShell syntax was slightly off. Switching to cross-env solved it for the whole team instantly.
Steven, variables set with set or $env: are only "session-scoped," meaning they disappear the moment you close the window. If you want a persistent variable, you would need to use setx NODE_ENV production in CMD, which writes it to the registry. However, be careful with setx because it makes the variable global for all Node apps on your machine. For specific projects, using a .env file with the dotenv package is a much safer way to manage persistent production settings without cluttering your system's global environment.