Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put a nextjs app in maintenance mode (using Vercel)

I've just released my nextjs app to production using Vercel.

I'm loving the whole experience except for one tiny part: I would have loved to be able to put my app in maintenance mode, but this option does not seem available on Vercel.

My question is: Has anyone achieved this before and could share some details here?

I'm guessing it could be done at 2 levels:

  • Modifying my app so that if an environment variable (i.e MAINTENANCE_MODE=true) is detected, every page redirects to a maintenance screen. However, this is not ideal, because adding an environment variable on Vercel requires a deployment for it to be taken into account.
  • Having a simple per-project toggle to enable/disable maintenance mode from Vercel. That would be mind-blowing.
like image 591
Marc Perrin-Pelletier Avatar asked Jun 08 '20 14:06

Marc Perrin-Pelletier


People also ask

Is next JS with Vercel?

Performance optimizations built into Next. js are automatically supported and enhanced on Vercel, creating smooth, interactive experiences that feel instant for every user.


2 Answers

"Maintenance Mode" can be achieved with an Environment Variable and redirects property in your next.config.js (requires Next.js 9.5.0 or newer).

module.exports = {
  redirects() {
    return [
      process.env.MAINTENANCE_MODE === "1"
        ? { source: "/((?!maintenance).*)", destination: "/maintenance.html", permanent: false }
        : null,
    ].filter(Boolean);
  }
};

This adds a wildcard route that matches incoming requests and then issues a temporary redirect the /maintenance.html location.

Note that you cannot make changes to a deployment (config or environment variables) without deploying again.


Old Answer

If you're not using Next.js or using an old version of Next.js, "Maintenance Mode" can be achieved with the redirects property in vercel.json.

{
  "redirects": [
    { "source": "/((?!maintenance).*)", "destination": "/maintenance.html", "permanent": false }
  ]
}
like image 122
styfle Avatar answered Oct 20 '22 13:10

styfle


A different solution I am currently using would be to create a separate maintenance page and then conditionally intercept the rendering of the actual component based on an environment variable.

I achieve this by adjusting the _app.js code to:

function MyApp({ Component, pageProps }) {
  if (process.env.NEXT_PUBLIC_MAINTENANCE_MODE === 'false') {
    return <Component {...pageProps} />
  } else {
    return <Maintenance />
}

Note that as mentioned in earlier answers, this relies on the Vercel env variables, per their website: "A new Deployment is required for your changes to take effect."

like image 34
Fesch Avatar answered Oct 20 '22 13:10

Fesch