Open In App

How to Fix the “NODE_ENV is not recognized” Error in Node JS

We generally come across the error message “NODE_ENV is not recognized as an internal or external command, operable command, or batch file” while trying to set an environment variable in a package.json script in Node JS. This guide will assist you in resolving the issue with a straightforward solution.

When using the following syntax in a Windows environment, it won’t work as expected:



"scripts": {
"test": "NODE_ENV=test mocha",
},

This leads to the error message:

“NODE_ENV” is not recognized as an internal or external command, operable command or batch file.



Example: Below is the code example which generate error.




//app.js
const express = require('express');
const app = express();
const port = 3000;
 
// set session in the / route
app.get('/', (req, res) => {
    // session variable
    res.send(`<h1>Hey Geek!</h1>`);
});
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});




//package.json
"scripts": {
   "start": "NODE_ENV= node app.js"
 }

Output:

Output

To overcome this issue, this is how you set an environment variable in windows:

"scripts": {
"test": "SET NODE_ENV=test & mocha ",
},

After making this adjustment, the “NODE_ENV” error should no longer occur, and your script will execute without any issues.

Example: Below is the code example which generate error.




//app.js
const express = require('express');
const app = express();
const port = 3000;
 
// set session in the / route
app.get('/', (req, res) => {
    // session variable
    res.send(`<h1>Hey Geek!</h1>`);
});
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});




//package.json
"scripts": {
   "start": "cross-env NODE_ENV=production node app.js"
 }

Output:

Output


Article Tags :