Reputation: 83
Trying to implement maintenance mode using middleware.
If i try NextResponse.next()
after the rewrite, website loads normally and does not go to
maintenance page. I got correct response with html page in network tab, but its not showing.
If i try redirect instead of rewrite i got "The page isn’t redirecting properly"
from firefox which indicate that there is too much redirects.
Does my next config have some bad redirects/rewrites or this does not work?
middleware.ts
import { NextRequest, NextResponse } from "next/server";
import { get } from "@vercel/edge-config";
export async function middleware(req: NextRequest) {
try {
const isInMaintenanceMode = await get<boolean>("isInMaintenanceMode");
if (!isInMaintenanceMode) {
if (req.nextUrl.pathname === "/maintenance") {
req.nextUrl.pathname = `/`;
return NextResponse.redirect(req.nextUrl);
}
} else {
req.nextUrl.pathname = `/maintenance`;
return NextResponse.rewrite(req.nextUrl);
}
} catch (error) {
console.error(error);
}
}
next.config
const nextConfig = {
experimental: { esmExternals: true },
reactStrictMode: true,
async rewrites() {
return [
{
source: "/pages/1",
destination: "/",
},
{
source: "/1",
destination: "/",
},
{
source: "/pages/:page",
destination: "/:page",
},
];
},
async redirects() {
return [
{
source: "/:page((?:10[1-9])|(?:10[0-9]{2,}))",
destination: "/pages/100",
permanent: true,
},
{
source: "/pages/:page((?:10[1-9])|(?:10[0-9]{2,}))",
destination: "/pages/100",
permanent: true,
},
{
source: "/pages/:page((?:-[0-9]+)|(?:0))",
destination: "/pages/1",
permanent: true,
},
{
source: "/:page((?:-[0-9]+)|(?:0))",
destination: "/pages/1",
permanent: true,
},
];
},
};
Edit: Menaged to solve it by adding a matcher:
export const config = {
matcher: ["/:pages*"],
};
But it throw some random error:
SyntaxError: expected expression, got '<'
So i had to exclude all routes that use _next per this post:
https://stackoverflow.com/a/73903823/13292884
export const config = {
matcher: ["/((?!_next|api/auth).*)"],
};
Upvotes: 1
Views: 1262