NextJS in Maintenance Mode
Adam C. |

Everyone hates the server is down, but it happens sometimes. It's better you have a backup plan, that you can quickly switch to, but if not, at least you need to put the site in the maintenance mode, so your visitors won't be surprised by seeing the 404 or 500 error. In this article, I would like to show you how to put on a maintenance page quickly in the NextJs application.

Photo by Coby Shimabukuro on Unsplash

First of all, you need to create a static maintenance page, that you can put in the next/public folder, so then it can be accessed via https://YOUR-WEBSITE/maintenance.html. It could be as simple as this one: https://gist.github.com/pitch-gist/2999707

Then in the next.config.js add the following block:

module.exports = {
  ... // your other settings
  async redirects() {
    return [
      {
        source: "/((?!maintenance).*)",
        destination: "/maintenance.html",
        permanent: false, //!!!IMPORTANT!!!
      },
    ];
  },
};

Then deploy your code. In my case, I run ‘npm run build' and then “pm2 restart myApp”, after that all traffic will be temporarily redirected to the maintenance.html page. 

Very important!!! - set the “permanent" to be false, otherwise, the browser will cache the redirect, then it will cause issue after you disable the maintenance mode.

Then fix your server issue, after that, bring the site when it's ready by updating the next.config.js to be:

module.exports = {
  ... // your other settings
  async redirects() {
    return [
      // {
      //   source: "/((?!maintenance).*)",
      //   destination: "/maintenance.html",
      //   permanent: false,
      // },
      {
        source: "/maintenance.html",
        destination: "/",
        permanent: false,
      },
    ];
  },
};

Note that I commented out the redirection, and add another one to redirect “maintenance.html” to the homepage, so when the user refreshes the maintenance page after the site is back, she/he can be sent back to the homepage.

That's it. Next, you should think of a backup plan to minimize downtime.