🏠 Home

Why does SIGTERM/SIGINT handling not working in NextJS?

With NextJS version 12.2.0, we can handle shutdowns manually. If you have problems getting it work, maybe you should check out some areas we discuss here.

Setup

Let’s review how to set it up.

  1. Set the environment variable to allow for manual SIGTERM/SIGINT handling.
  • Set NEXT_MANUAL_SIG_HANDLE to true
  1. Add handlers in pages/_document.js, right below the default Document function.
if (process.env.NEXT_MANUAL_SIG_HANDLE) {
  process.on('SIGTERM', () => {
    console.log('Received SIGTERM: ', 'cleaning up');
    process.exit(0);
  });
  process.on('SIGINT', () => {
    console.log('Received SIGINT: ', 'cleaning up');
    process.exit(0);
  });
}

Checklist

  • Make sure you set NEXT_MANUAL_SIG_HANDLE properly
    • Do not set it in .env or .env.* files because next server does not read it. It does not use dotenv or similar packages to read .env files.
    • You can set it in Dockerfile ENV NEXT_MANUAL_SIG_HANDLE true or in npm scripts
      {
        // ...
        "scripts": {
          "dev": "NEXT_MANUAL_SIG_HANDLE=true next dev",
          "start": "NEXT_MANUAL_SIG_HANDLE=true next start",
          //...
        },
        //...
      }
      
  • Use the right termination commands
    • In the terminal, or you can just use ctrl + c.
      # Use the correct PID
      kill -s SIGTERM $PID
      # Or
      kill -s SIGINT $PID
      
    • In node
      process.kill(process.pid, "SIGTERM");
      

Reference