Is there a way to place a Next.js application into maintenance mode on Vercel?

After successfully launching my nextjs application on Vercel, I've been thoroughly impressed with the overall process.

However, there is one minor aspect that I wish could be improved: the ability to easily activate a maintenance mode for my app. Unfortunately, it seems that this feature is not currently available on Vercel.

So, my inquiry is: Has anyone encountered this issue before and found a solution they can share?

I am considering two possible approaches:

  • Adapting my app so that if it detects a specific environment variable (such as MAINTENANCE_MODE=true), it automatically redirects users to a maintenance screen. However, this solution has its drawbacks since updating an environment variable on Vercel requires a new deployment to take effect.
  • Implementing a straightforward toggle within Vercel that would allow me to effortlessly enable or disable maintenance mode for my project. This would truly be a game-changer.

Answer №1

"To activate "Maintenance Mode," you can utilize an Environment Variable along with the redirects feature in your next.config.js file (make sure to use Next.js version 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 code snippet creates a wildcard route that captures incoming requests and then temporarily redirects them to the /maintenance.html location.

Please note that any modifications to the deployment settings or environment variables require a new deployment to take effect.


Previous Solution

If you're not using Next.js or running an outdated version, you can implement "Maintenance Mode" by utilizing the redirects property in your vercel.json configuration file.

{
  "redirects": [
    { "source": "/((?!maintenance).*)", "destination": "/maintenance.html", "permanent": false }
  ]
}

Answer №2

To approach this issue differently, I have implemented a unique solution by developing a dedicated maintenance page and conditionally intercepting the rendering of the main component based on an environment variable.

To accomplish this customization, I made adjustments to the _app.js code as follows:

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

It is important to note that, similar to previous suggestions, this method relies on Vercel environment variables. As stated on their platform: "A new Deployment is required for your changes to take effect."

Answer №3

Building on what was mentioned by @ptrkcsk, if you decide to create a maintenance page within the pages directory and are using the <Image> component from next/image to render images, don't forget to include your static folder in the redirects regex as well.

Here is the source pattern that has been effective for me:

/((?!maintenance)(?!_next)(?!static).*)

Answer №4

Vercel has introduced a new method for implementing maintenance mode in 2023 without the need for re-deployment. You can check out Vercel's Example App: Maintenance Page.

This approach involves utilizing Vercel's Edge Config and Next.js Middleware.

  1. To begin, define a key called isInMaintenanceMode in the Edge Config of your project. Any changes made to the Edge Config storage are quickly propagated (around 10 seconds according to Vercel). However, there are limitations such as not being able to read it from any location. This also comes with a cost as noted in the documentation.
  2. In your Next.js project, create a file named middleware.js which will verify the value of isInMaintenanceMode and adjust the routing accordingly:
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 determine if the maintenance page should be displayed
  const isInMaintenanceMode = await get('isInMaintenanceMode')

  // If maintenance mode is active, redirect the URL pathname to the maintenance page
  if (isInMaintenanceMode) {
    req.nextUrl.pathname = `/maintenance`

    // Rewrite the URL
    return NextResponse.rewrite(req.nextUrl)
  }
}

Answer №5

  1. If there isn't already a file named _app.js in the pages directory, create one.

  2. Copy and paste the code below into the newly created file:

import React from 'react';

function MyApp({ Component, pageProps }) {
  const maintenanceMode = true; // Change this to false when maintenance is complete
  const MaintenancePage = () => <div>Maintenance mode</div>;
  
  return (
    <>
      {maintenanceMode ? <MaintenancePage /> : <Component {...pageProps} />}
    </>
  );
}

export default MyApp;
  1. Modify the <MaintenancePage> component to suit your needs.

  2. To activate maintenance mode, set the maintenanceMode variable to true. Once maintenance is finished, revert it back to false.

  3. You can also customize the styling of the maintenance page by creating a CSS file if desired.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

No solution was found for implementing Airbnb TypeScript in React.js (Next.js) using ESLint

screenshot I encountered an issue where I couldn't locate the Airbnb typescript option in React JS (Next JS) within ESLint. Prior to this, I had installed Storybook and mistakenly clicked "yes" when prompted to migrate ESLint to Storybook. ...

Having trouble identifying the dotenv package when running `dotenv -e .env.dev yarn dev` in a Next.js project

After building a next.js project, I decided to incorporate dotenv by using the following command: yarn global add dotenv-cli All other packages were successfully installed using yarn, but when attempting to execute the command: dotenv -e .env.dev yarn dev ...

Tips for leveraging the functions service in Next.js for better code reusability

I am just starting to learn Next.js and I have a preference for organizing my API functions in a separate folder called services. I attempted to implement some code based on this topic but unfortunately, it did not work as expected. It seems like my api fu ...

Solving the issue of font awesome override in nextJS

Currently, I am integrating FontAwesome into my NextJS project with Tailwind CSS. Following the official documentation, it instructs to add the given code snippet to _app.tsx file: import { config } from "@fortawesome/fontawesome-svg-core"; impor ...

Is it really a smart idea to have an abundance of conditionals running in a middleware in next.js? Let's explore

I am in the process of revamping an application with Next.js and have some concerns about potential inefficiencies due to running multiple conditionals within the new "_Middleware" as it is triggered on every single request. I have implemented the code bel ...

What is causing styled-components to include my attributes in the DOM?

In various parts of my code, there is a snippet like this: import React from 'react' import styled from 'styled-components' type PropsType = { direction?: 'horizontal' | 'vertical' flex?: number | string width ...

Tips for creating successful tests for a project that includes i18n functionality

I have been working on a Next.js project for some time now. The project includes i18n support, and I'm keen to write unit tests for it. However, I've hit a roadblock in figuring out the most effective way to approach writing these tests. Should I ...

Tips for avoiding components from re-rendering when switching between browser tabs

When I switch browser tabs in my Next.js app, the component gets re-rendered. For example, if the app is open on tab 1 and then I switch to tab 2 before returning to tab 1. The issue arises when I have a page displaying a list of records, and after filter ...

Trouble accessing session cookie during server-side request with getServerSideProps in Next.js

I'm currently facing an issue where I am trying to make a request to a backend service using Axios in getServerSideProps, but it is unsuccessful because the necessary session cookie for authentication is not included in the context.req headers. In th ...

When the tab is switched, the URL remains the same. However, if the URL is changed,

The tabs are changing content but the URL is not being updated. Please refer to this link for a clearer explanation of my issue: https://codesandbox.io/s/mui-tabs-58y4gk Whenever I click on a tab, the URL should change accordingly (for example, clicking ...

Error: Type Error when using custom App and getInitialProps in Next.js

I have a simple app built using the Next JS starter kit, and I am attempting to integrate custom functionality as outlined in the documentation: class MyApp extends App { static async getInitialProps({ Component, router, ctx }) { let pageProps = {}; ...

Do you need to incorporate 'next-redux-wrapper' into a 'Next.js + Redux Toolkit' project if you are solely using 'static generation'?

I am currently in the process of developing a Next.js application using Redux Toolkit for managing state. My approach involves utilizing Static Generation through getStaticProps and getStaticPaths. My question is whether it is necessary to incorporate nex ...

Having trouble importing Tone.js in your Next.js project?

Having trouble importing Tone in my Next.js project. Despite having Tone as a dependency, I face an issue when trying to run import * as Tone from 'tone'. Next.js shows an error stating it can't locate the module node_modules/tone/build/esm/ ...

Strategies for resolving the "Objects are invalid React children" issue in Next.js 13 and Next Auth

I am currently developing an application using Next JS 13 with Firebase and Next Auth. After integrating Firebase with Next Auth and utilizing the session, I encountered an error. Error: Objects are not valid as a React child (found: [object Promise]). If ...

Unable to create a cookie in server action of Next.js version 13.4

Having trouble setting a cookie in actions and encountering an error: Cookies can only be modified in a Server Action or Route Handler, even though I have them in the server action. The file path is located in app/actions.ts import { cookies } from " ...

Is it safe to establish a direct connection between NextJS and MongoDB without any intermediary services?

When it comes to connecting NextJS on a Digital Ocean droplet directly to MongoDB running on another Digital Ocean virtual server, there seems to be conflicting opinions. Some argue against using "full stack" frameworks like NextJS or Angular without an in ...

Discover the steps to deploy NextJS on AWS with the same efficiency as Vercel

For my POC, I am looking to deploy NextJS on AWS using AWS CDK and exploring different options. The NextJS docs suggest running npm run build && npm start to start the service, but this may not be the most optimized way. Vercel offers a highly opt ...

The object literal can only define existing properties, and the property 'x' is not found in the type (prisma)

Trying to incorporate two new items into a table in my Prisma schema has been challenging. Once I update the database with Prisma DB push and attempt to create new data for the table, issues arise. While everything functions correctly on my localhost, depl ...

What could be causing the error message to appear stating that each list item must have a unique key when utilizing react-bootstrap in Nextjs?

My file currently contains keys for each child component, but it is still raising an error internally. I am unsure if I can resolve these issues on my own. export default function SecondaryNav(props:NavItems) { const router = us ...

Is MongoDB's find() method returning incorrect objects?

My current task involves running a Mongo query on the Order database to retrieve orders associated with a specific user by using their email. This process is achieved through an API, but I'm encountering difficulties as the returned object contains un ...