Anonymous HTML was sent with 'public, max-age=60, s-maxage=300, stale-while-revalidate=300'. After a rebuild the old chunk URLs (keyed by deploy id) are deleted, so any browser/CDN holding the stale HTML got 404s for up to five minutes. Since the deploy id is the git commit, the HTML must be re-fetched after every deploy; only content-hashed static assets should be cached. Return no-store for all HTML documents.
63 lines
2.0 KiB
TypeScript
63 lines
2.0 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { getToken } from "next-auth/jwt";
|
|
import { env } from "@/env";
|
|
import { buildContentSecurityPolicy, createCspNonce } from "@/lib/csp";
|
|
import { shouldRedirectAdminRequest } from "@/lib/proxy-access";
|
|
|
|
const SECURITY_HEADERS: Record<string, string> = {
|
|
"X-Content-Type-Options": "nosniff",
|
|
"X-Frame-Options": "DENY",
|
|
"X-XSS-Protection": "0",
|
|
"Referrer-Policy": "strict-origin-when-cross-origin",
|
|
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
|
|
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
|
|
};
|
|
|
|
export const proxy = async (req: import("next/server").NextRequest) => {
|
|
const token = await getToken({
|
|
req,
|
|
secret: env.AUTH_SECRET,
|
|
secureCookie: true,
|
|
});
|
|
|
|
if (shouldRedirectAdminRequest(req.nextUrl.pathname, token)) {
|
|
return NextResponse.redirect(new URL("/login", req.url));
|
|
}
|
|
|
|
const nonce = createCspNonce();
|
|
const csp = buildContentSecurityPolicy(nonce);
|
|
|
|
const headers = new Headers(req.headers);
|
|
headers.set("x-pathname", req.nextUrl.pathname);
|
|
headers.set("x-nonce", nonce);
|
|
|
|
const ip =
|
|
req.headers.get("cf-connecting-ip") ??
|
|
req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
|
|
req.headers.get("x-real-ip") ??
|
|
"";
|
|
if (ip) headers.set("x-real-client-ip", ip);
|
|
|
|
const response = NextResponse.next({ request: { headers } });
|
|
|
|
// HTML is never cached (browser/CDN/edge) so that after a deploy the page
|
|
// always references the current build's chunks. Static assets are
|
|
// content-hashed + immutable and can be cached aggressively; a stale HTML
|
|
// document would reference chunk URLs that no longer exist after a rebuild.
|
|
response.headers.set(
|
|
"Cache-Control",
|
|
"private, no-cache, no-store, max-age=0, must-revalidate",
|
|
);
|
|
|
|
for (const [key, value] of Object.entries(SECURITY_HEADERS)) {
|
|
response.headers.set(key, value);
|
|
}
|
|
response.headers.set("Content-Security-Policy", csp);
|
|
|
|
return response;
|
|
};
|
|
|
|
export const config = {
|
|
matcher: ["/((?!api|_next/static|_next/image|assets|favicon.ico).*)"],
|
|
};
|