Search code examples
node.jsnode-modulesrender

Dev dependency for NodeJS API in production


I am beginner in NodeJS. I am currently working on NodeJS API project and hosted to Render with node_env in production.

But in the cloud environment, I received error:

"Error: Cannot find module 'morgan'"

that I guess is one of dev dependency library is not installed. Initially, I set up the hosting platform build command of installation of libs with npm install then I changed to npm install --dev and it able to work.

So my question:

  1. Currently, my code consists of both prod and dev env, I used if statement to disable dev code during prod env. But now when I host the server I still need to install dev dependency since dev env code still in the program, so I want to ask what is the best practice for dev and prod env for NodeJS api?
  2. Is there any way, we do not need to install dev dependency in prod

Package.js

  "name": "bnndirect_api",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "express-mongo-sanitize": "^2.2.0",
    "express-rate-limit": "^7.1.5",
    "helmet": "^7.1.0",
    "hpp": "^0.2.3",
    "perfect-express-sanitizer": "^1.0.13"
  },
  "devDependencies": {
    "morgan": "^1.10.0",
    "nodemon": "^3.0.2"
  }
}

My dev code in server.js that uses that lib

    const morgan = require("morgan");
// DEV LOGGING MIDDLEWARE
    if (process.env.NODE_ENV === 
    "development") {
    app.use(morgan("dev"));
    }

Solution

  • You are using morgan even before it is installed. i.e, in your production environment, you haven't installed morgan. But you have added a require('morgan') statement there which will try to use morgan in your code. You can update your code like this:

    // DEV LOGGING MIDDLEWARE
    if (process.env.NODE_ENV === "development") {
        const morgan = require("morgan");
        app.use(morgan("dev"));
    }