javascriptreactjsnode.jsnext.js

NextJS NodeJS multi processes


I use NextJS for frontend development and NodeJS for backend development. I want to use child processes. How can I set NodeJS up. How can I use multiple processes for my NextJS application. Can anyone provide me with a sample code for it?


Solution

  • I think you are looking for this

    or,

    https://stackoverflow.com/a/72831318/13086781

    This is just a sample code that I wrote like 2 years ago. It should still work.

    const express = require("express");
    const next = require("next");
    const cluster = require("cluster");
    const os = require("os");
    
    const dev = process.env.NODE_ENV !== "production";
    const app = next({ dev });
    const handle = app.getRequestHandler();
    
    //if the cluster is master
    if (cluster.isMaster) {
      for (let i = 0; i < numCpu; i++) {
        cluster.fork();
      }
    
      //if worker dies or is killed
      cluster.on("exit", (worker, code, signal) => {
        cluster.fork();
      });
    } else {
      app
        .prepare()
        .then(() => {
          const server = express();
    
          server.all("*", (req, res) => {
            return handle(req, res);
          });
    
          server.listen(port, (err) => {
            if (err) throw err;
            console.log(`> Ready on http://localhost:${port}`, process.pid);
          });
    
        })
        .catch((ex) => {
          console.error(ex.stack);
          process.exit(1);
        });
      }