Fix a proxy.ts that sends mixed-case addresses like /Teas/Mint-Tea to their lowercase page
Leaf and Kettle's old site had addresses like /Teas/Mint-Tea, and flyers and other sites still link to them. Next.js matches routes letter for letter, so those links now get a 404. A teammate wrote this proxy.ts to send them to the lowercase page, but it isn't right yet. Fix it.
A path with any capital letter gets a permanent redirect, 308, to the same path in lowercase. Only the path changes: the query comes along exactly as it was, since values like ?ref=Spring-Flyer are data, not part of the address. A path that's already lowercase goes on to its page.
config.matcher keeps proxy.ts away from Next.js's own files (every path under /_next/), from the API (/api and every path under /api/), which programs call by its exact paths, and from every path with a dot, like /images/Leaf.PNG, since Next.js serves the files in public by their exact names.
proxy.tsimport { NextResponse, type NextRequest } from "next/server";
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
if (pathname !== pathname.toLowerCase()) {
return NextResponse.redirect(new URL(pathname.toLowerCase(), request.url));
}
}
- redirects a path with capitals to its lowercase form, for good
- keeps the query exactly as it was
- lets lowercase paths through, whatever the query says
- runs for pages, not for Next.js's files, the API, or files from public
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…