Next.js Discord

Discord Forum

Middleware Help

Answered
Lord_TCG#9068 posted this in #help-forum
Open in Discord
Am I missing something? I thought if my middleware would throw an error, and I had an error.js file in the app folder, that file would show?

// middleware.js
import { NextResponse } from "next/server";
import setup from "./components/maintenance/setup.json";

export function middleware(request) {
  if (setup.maintenanceMode === true) {
    return NextResponse.error(new Error("Service Unavailable"), {
      status: 503,
    });
  }

  // Continue with the required route if maintenanceMode is false
  return NextResponse.next();
}

export const config = {};

// copied error.js from the docs
"use client"; // Error components must be Client Components

import { useEffect } from "react";

export default function Error({ error, reset }) {
  useEffect(() => {
    // Log the error to an error reporting service
    console.error(error);
  }, [error]);

  return (
    <div>
      <h2>Something went wrong!</h2>
      <button
        onClick={
          // Attempt to recover by trying to re-render the segment
          () => reset()
        }
      >
        Try again
      </button>
    </div>
  );
}


The if check works because the app runs normally if !==true, but if it is true, all I get is a blank white page and the dev tools show no content either....
Answered by joulev
what you should do instead is to make a page, say, /errors/maintenance-mode, then rewrite to that page when the site is under maintenance
View full answer

11 Replies

what you should do instead is to make a page, say, /errors/maintenance-mode, then rewrite to that page when the site is under maintenance
Answer
@joulev what you should do instead is to make a page, say, `/errors/maintenance-mode`, then rewrite to that page when the site is under maintenance
I was worried about an SEO hit from an orphaned link.

What I ended up doing temporarily was to check in the layout itself
{isMaintenance ? <Maintenance /> : children}
Not sure on the hit that will take for performance 🤔
@Lord_TCG#9068 I was worried about an SEO hit from an orphaned link. What I ended up doing temporarily was to check in the layout itself ` {isMaintenance ? <Maintenance /> : children}`
SEO wise I think you can use noindex or some similar meta tags

About your approach, yes it works but I think it will still run the page when the user loads them, so it will be slower
@joulev what you should do instead is to make a page, say, `/errors/maintenance-mode`, then rewrite to that page when the site is under maintenance
I'm going around in circles trying to implement this within the middleware.

I opted to use an npm script to toggle a json value from true or false. I opted for json over env because I could edit this dynamically without the need for a server restart (as I believe env is compiled and build and runtime?).

Anyway, at first I tried something like
import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'

export function middleware(req) {
  const maintenanceModeFilePath = path.resolve('./maintenanceMode.json')
  const maintenanceModeFile = fs.readFileSync(maintenanceModeFilePath)
  const { maintenanceMode } = JSON.parse(maintenanceModeFile)

  if (maintenanceMode) {
...


But path returns the error The edge runtime does not support Node.js 'path' module.. Then I considered an fetch request but that looks for a URL not a file path 🤔

Any advice would be great
@joulev Are you self hosting on your own VPS or on platforms like Vercel?
I have a pretty unlimited cpanel host, which has node apps support.

Currently I'm testing locally
@Lord_TCG#9068 I have a pretty unlimited cpanel host, which has node apps support. Currently I'm testing locally
I see. In that case I think simply importing the json file will work
@joulev I see. In that case I think simply importing the json file will work
Oh damn that does work. I was way overcomplicating this.

Thanks again!