Logo

dev-resources.site

for different kinds of informations.

Maintenance mode check in Next.js middleware.ts

Published at
1/3/2025
Categories
opensource
nextjs
vercel
Author
ramunarasinga-11
Categories
3 categories in total
opensource
open
nextjs
open
vercel
open
Author
16 person written this
ramunarasinga-11
open
Maintenance mode check in Next.js middleware.ts

In this article, we review the code related to maintenance mode check in Grida source code, but first we need to understand what a maintenance mode is in Vercel.

Image description

Maintenance mode in Vercel

I am quoting the documentation found in Maintenance Page Example

below:

When we do a release, promotion, event, etc. that might bring more attention than usual to a page;

Its a good idea to have a backup plan that includes showing a different page to the users in case something fails. If this page receives a lot of traffic, we can use the edge, a previously generated static page and Edge Config to give the users dynamic at the speed of static.

You would use Maintenance Page when you want to change the flow of the traffic quickly in case something fails, but how to do it?

Detect if your app is in maintenance mode

The below code is picked from the Maintenance Page example.

import { NextRequest, NextResponse } from 'next/server'
import { get } from '@vercel/edge-config'

export const config = {
 matcher: '/big-promo',
}

export async function middleware(req: NextRequest) {
  // Check Edge Config to see if the maintenance page should be shown
  const isInMaintenanceMode = await get('isInMaintenanceMode')
  // If in maintenance mode, point the url pathname to the maintenance page
  if (isInMaintenanceMode) {
    req.nextUrl.pathname = `/maintenance`
    // Rewrite to the url
    return NextResponse.rewrite(req.nextUrl)
  }
}
Enter fullscreen mode Exit fullscreen mode

Here the most important check is about maintenance mode

// Check Edge Config to see if the maintenance page should be shown
const isInMaintenanceMode = await get('isInMaintenanceMode')
Enter fullscreen mode Exit fullscreen mode

Then if your project is in maintenance mode, you would do something like below, to show the maintenance page:

// If in maintenance mode, point the url pathname to the maintenance page
if (isInMaintenanceMode) {
  req.nextUrl.pathname = `/maintenance`
  // Rewrite to the url
  return NextResponse.rewrite(req.nextUrl)
}
Enter fullscreen mode Exit fullscreen mode

Github discussion:

There is a discussion on Github about Maintenance mode in Vercel.

Some suggestions involve using redirects in next.config.ts depending on an enviroment variable called MAINTENANCE_MODE but what folows that is a conversation about how this be indexed by Google and for that reason, comment suggests to add <meta name=”robots” content=”noindex” />

The accepted answer points to the Maintenance page example.

Maintenance mode check in Grida Form

The below code is picked from forms/middleware.ts

export async function middleware(req: NextRequest) {
  // #region maintenance mode
  if (process.env.NODE_ENV === "production") {
    try {
      // Check whether the maintenance page should be shown
      const isInMaintenanceMode = await get<boolean>("IS_IN_MAINTENANCE_MODE");

      // If is in maintenance mode, point the url pathname to the maintenance page
      if (isInMaintenanceMode) {
        req.nextUrl.pathname = `/maintenance`;

        // Rewrite to the url
        return NextResponse.rewrite(req.nextUrl);
      }
    } catch (error) {
      // show the default page if EDGE_CONFIG env var is missing,
      // but log the error to the console
      console.error(error);
    }
  }
  // #endregion maintenance mode
Enter fullscreen mode Exit fullscreen mode

This code handles the maintenance mode exactly as what is provided in the Vercel’s example, but there are slight differences:

  1. Try/catch block

  2. process.env.NODE_ENV check

This defensive mechanism is important to handle any unexpected errors and that to apply the maintenance mode only in production.

About me:

Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.

I am open to work on interesting projects. Send me an email at [email protected]

My Github — https://github.com/ramu-narasinga

My website — https://ramunarasinga.com

My Youtube channel — https://www.youtube.com/@thinkthroo

Learning platform — https://thinkthroo.com

Codebase Architecture — https://app.thinkthroo.com/architecture

Best practices — https://app.thinkthroo.com/best-practices

Production-grade projects — https://app.thinkthroo.com/production-grade-projects

References:

  1. https://github.com/gridaco/grida/blob/main/apps/forms/middleware.ts#L14

  2. https://github.com/vercel/next.js/discussions/12850

  3. https://vercel.com/templates/next.js/maintenance-page

  4. https://github.com/vercel/next.js/discussions/12850#discussioncomment-3335807

  5. https://github.com/gridaco/grida/blob/main/apps/forms/middleware.ts#L14

vercel Article's
30 articles in total
Favicon
Github Actions with Vercel in 2024
Favicon
Deploy laravel application using vercel : Amazing
Favicon
Building a Twitter OAuth Authentication Header Generator with Vercel Serverless Functions
Favicon
This Serverless Function has crashed. Your connection is working correctly. Vercel is working correctly.
Favicon
How to Host a Project on Vercel Using a GitHub Repository
Favicon
Page can't be indexed in Google Search Console
Favicon
PSA: Add the following to your Vercel project's firewall
Favicon
Deploying an Existing Express API + Prisma + Supabase Project to Vercel
Favicon
Next 14 Rate Limiting made easy
Favicon
Vercel asking for env variable I already provided...
Favicon
I like Vercel Deployments
Favicon
SNAP PHOTOGRAPHY WEBAPP
Favicon
Web development - Vercel AI
Favicon
Maintenance mode check in Next.js middleware.ts
Favicon
Journey to first release of "remozine.com"
Favicon
How I Built an Affordable, Efficient Architecture for a Daily Movie Puzzle Game
Favicon
Deploying Your Node.js Backend for Free on Vercel
Favicon
Deploy Laravel to Vercel
Favicon
Un blog statique sur mesure avec Notion headless
Favicon
Export .env from Vercel: New Laptop, Old Project? No Problem!
Favicon
Next.js & Hono.js Starter Project 🚀
Favicon
How I Got Over My Fear of Launching by Building a Simple Tool in a Few Hours
Favicon
How to create free email forwarding for your Vercel app custom domain
Favicon
How to Host Hugo in Vercel
Favicon
Automating Your Project Deployment with GitHub Actions: A Step-by-Step Guide
Favicon
Fast and Simple NestJS App Deployment on Vercel
Favicon
How to Optimize Vercel Costs
Favicon
5 Vercel Features Developers Absolutely Love
Favicon
Deploying a Node.js + Express Server to Vercel Using the CLI
Favicon
How to deploy a simple website to Vercel: case of a portfolio

Featured ones: