'Restart NodeJS app automatically after app crashes

I want to add code to my NodeJS (Express) app so that it will restart automatically after crashes with some error. I know about forever npm package, but I found only examples with running app in development, while my goal is to use it in production (app is already on production server). Should I add some code inside app.js (main file for my application) or in different files?

Here's my app.js code:

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const path = require("path");
const con = require("./databaseConnection");

const app = express();

/* Middleware */
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

/* Redirect http to https */
app.enable('trust proxy');
app.use (function (req, res, next) {
    if (req.secure) {
        // request was via https, so do no special handling
        next();
    } else {
        // request was via http, so redirect to https
        res.redirect('https://' + req.headers.host + req.url);
    }
});

/* Routers */
const authRouter = require("./routers/authRouter");
const userRouter = require("./routers/userRouter");

app.use("/auth", authRouter);
app.use("/user", userRouter);

app.listen(5000);


Solution 1:[1]

I think the program you are looking for is pm2. https://pm2.keymetrics.io/docs/usage/quick-start/

You could listen for any unhandled exceptions/errors and handle them to stop the server crashing because of an uncaught error, but there are a bunch more problems that could happen with the process itself that would go unhandled such as memory leaks, which is why you need to use a process manager rather than something internal inside your express server.

It's better to use the pm2 daemon to manage the server processes for you, it also comes with a built-in dashboard, logging, and useful restarting configuration options such as

  • Restart app at a specified CRON time
  • Restart app when files have changed
  • Restart when app reach a memory threshold
  • Delay a start and automatic restart
  • Disable auto restart (app are always restarted with PM2) when crashing or exiting by default)
  • Restart application automatically at a specific exponential increasing time

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Conor Reid