import { NextRequest, NextResponse } from "next/server";
import { detectLocaleFromHeaders } from "@/lib/i18n/detect";
import { pathLocale, replacePathLocale } from "@/lib/i18n/path";
import {
canonicalPublicAuthPath,
publicAuthCallbackDestination,
} from "@/lib/public-auth-routes";
const COOKIE = "NEXT_LOCALE";
const SECURITY_HEADERS: Record<string, string> = {
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), interest-cohort=()",
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
};
function applySecurityHeaders(res: NextResponse): NextResponse {
for (const [k, v] of Object.entries(SECURITY_HEADERS)) res.headers.set(k, v);
return res;
}
* The one host this site is indexed under. `www` is also bound to this worker
* as a custom domain, so without this guard the entire site answers on two
* hosts and every page has a duplicate URL a crawler can reach.
*
* This runs before the locale and static-asset branches on purpose: the
* canonical host has to win for assets and API routes too, or a `www` page
* keeps pulling subresources from `www` after the document moved.
*/
const CANONICAL_HOST = "codewhale.net";
function canonicalHostRedirect(req: NextRequest): NextResponse | null {
const host = req.headers.get("host");
if (!host) return null;
const bare = host.split(":")[0].toLowerCase();
if (bare !== `www.${CANONICAL_HOST}`) return null;
const url = req.nextUrl.clone();
url.host = CANONICAL_HOST;
url.port = "";
return NextResponse.redirect(url, 301);
}
export function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const canonical = canonicalHostRedirect(req);
if (canonical) return applySecurityHeaders(canonical);
if (
pathname.startsWith("/api/") ||
pathname.startsWith("/_next/") ||
pathname === "/opengraph-image" ||
pathname.includes(".")
) {
return applySecurityHeaders(NextResponse.next());
}
const callback = publicAuthCallbackDestination(req.nextUrl);
if (callback) {
return applySecurityHeaders(NextResponse.redirect(callback, 307));
}
const canonicalAuth = canonicalPublicAuthPath(pathname);
if (canonicalAuth && canonicalAuth !== pathname) {
const url = req.nextUrl.clone();
url.pathname = canonicalAuth;
return applySecurityHeaders(NextResponse.redirect(url, 308));
}
const existing = pathLocale(pathname);
if (existing) {
const canonicalPath = replacePathLocale(pathname, existing);
let res: NextResponse;
if (canonicalPath === pathname) {
res = NextResponse.next();
} else {
const url = req.nextUrl.clone();
url.pathname = canonicalPath;
res = NextResponse.redirect(url, 308);
}
res.cookies.set(COOKIE, existing, { path: "/", maxAge: 60 * 60 * 24 * 365 });
return applySecurityHeaders(res);
}
const locale = detectLocaleFromHeaders(
req.cookies.get(COOKIE)?.value,
req.headers.get("accept-language"),
);
const url = req.nextUrl.clone();
url.pathname = `/${locale}${pathname}`;
const res = NextResponse.redirect(url);
res.cookies.set(COOKIE, locale, { path: "/", maxAge: 60 * 60 * 24 * 365 });
return applySecurityHeaders(res);
}
export const config = {
matcher: ["/:path*"],
};