Skip to content

Commit

Permalink
Add middleware to control maintenance mode
Browse files Browse the repository at this point in the history
  • Loading branch information
ruchernchong committed Nov 30, 2024
1 parent ec68847 commit 5670b90
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 9 deletions.
34 changes: 33 additions & 1 deletion app/maintenance/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,39 @@
"use client";

import { useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Maintenance } from "@/components/Maintenance";

const MaintenancePage = () => {
// Building it this way as I may add stuff to it later
const router = useRouter();
const searchParams = useSearchParams();

useEffect(() => {
const checkMaintenance = async () => {
try {
// TODO: Simulating this for now
const isMaintenanceMode = process.env.MAINTENANCE_MODE;

if (!isMaintenanceMode) {
const from = searchParams.get("from");
if (from) {
router.replace(decodeURIComponent(from));
} else {
router.replace("/");
}
}
} catch (e) {
console.error("Error checking maintenance status:", e);
}
};

const interval = setInterval(checkMaintenance, 5000);

void checkMaintenance();

return () => clearInterval(interval);
}, [router, searchParams]);

return <Maintenance />;
};

Expand Down
30 changes: 22 additions & 8 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,27 @@ import { NextRequest, NextResponse } from "next/server";
import { DOMAIN_NAME } from "@/config";

export const middleware = (request: NextRequest) => {
// TODO: Temporary method for now
const isMaintenanceMode = process.env.MAINTENANCE_MODE === "true";

if (
isMaintenanceMode &&
!request.nextUrl.pathname.startsWith("/maintenance")
) {
const maintenanceUrl = new URL("/maintenance", request.url);
maintenanceUrl.searchParams.set("from", request.url);
return NextResponse.redirect(maintenanceUrl);
}

const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
const cspHeader = `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline' *.${DOMAIN_NAME} *.googletagmanager.com;
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data:;
connect-src *;
font-src 'self';
`;
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline' *.${DOMAIN_NAME} *.googletagmanager.com;
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data:;
connect-src *;
font-src 'self';
`;

const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-nonce", nonce);
Expand Down Expand Up @@ -41,5 +53,7 @@ export const middleware = (request: NextRequest) => {
};

export const config = {
matcher: "/:path*",
matcher: [
"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};

0 comments on commit 5670b90

Please sign in to comment.