Baba
Baba

Reputation: 2229

Running node.js in a production environment mode

I am learning Node.js and this is my first code.

I created a file called server.js below with the code

server.js


        const express = require('express');
        const dotenv = require('dotenv');

        //load env vars
        dotenv.config({ path: './config/config.env'});

        const app = express();

        const PORT = process.env.PORT || 5000;

        app.listen(
            PORT,
            console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
        );

I have this section in my package.json file

package.json


         "scripts": {
            "start": "NODE_ENV=production node server",
            "dev": "nodemon server"
          },

Here is the content of my config.env file config.env


        NODE_ENV=development
        PORT=5000

When I run npm run dev everything is fine and runs

When I run npm start to run production, I get the error below.

'NODE_ENV' is not recognized as an internal or external command, operable program or batch file.

How can I resolve this? I need npm start to run

Upvotes: 0

Views: 7525

Answers (3)

Bisrat
Bisrat

Reputation: 121

For Windows:

"scripts": {
  "start": "node server.js",
  "dev": "set NODE_ENV=DEVELOPMENT && node server",
  "prod": "set NODE_ENV=PRODUCTION && node server"
}

For UNIX and other OS:

"scripts": {
  "start": "node server.js",
  "dev": "export NODE_ENV=DEVELOPMENT && node server",
  "prod": "export NODE_ENV=PRODUCTION && node server"
}

Upvotes: 2

Francisco
Francisco

Reputation: 11

An easy way to solve this problem:

npm install --save-dev cross-env

"start": "cross-env NODE_ENV=production node server"

This means that you don't have to worry about the platform

for read more: https://www.npmjs.com/package/cross-env

Upvotes: 1

Charlie
Charlie

Reputation: 23858

By the error message, you are running this in Windows. You need to use Set to setup an environment variable.

"scripts": {
            "start": "Set NODE_ENV=production&node server",
            "dev": "nodemon server"
          }

However, setting up environment variables in this manner is less secure and platform dependent. In other words, any attacker getting access to your server file system can set any environment variable by modifying the package.json. Also, if you decide to move your production to a Linux host later, your start script is going to be broken again.

So, the best practice is to set your environment variables via host configuration setup. Different cloud providers offer different methods for this.

Also, you might not need to use npm to run your script at all. You can call node server directly in your shell.

Upvotes: 0

Related Questions