Next.js Discord

Discord Forum

Prevent API routes from falling back to a page route

Unanswered
Kurilian Bobtail posted this in #help-forum
Open in Discord
Kurilian BobtailOP
I have a setup with a catch all page /app/[locale]/[[...page]]/page.tsx then a middleware to rewrite the locale into each request (excluding /api/** and /_next/**)

The issue is, if a route like /_next/random or /api/random is fetched (and doesn't exist) it falls back to the page route, meaning the 'locale' prop becomes 'api' or '_next' causing errors

Is there any way to prevent static files and api routes from falling back to pages?

2 Replies

Azawakh
Hello @Kurilian Bobtail
Here is some options for help you.

You can prevent static files and API routes from falling back into the catch-all page by exiting early in middleware and by ignoring those paths in your route matcher. For example:

export function middleware(req) {
const pathname = req.nextUrl.pathname;

// Don't touch /api or /_next
if (pathname.startsWith("/api") || pathname.startsWith("/_next")) {
return NextResponse.next();
}

// Locale handling
const hasLocale = /^/[a-z]{2}(/|$)/.test(pathname);
if (!hasLocale) {
const url = req.nextUrl.clone();
url.pathname = /en${pathname};
return NextResponse.rewrite(url);
}

return NextResponse.next();
}

export const config = {
matcher: ["/((?!api|_next).*)"],
};


This ensures missing /api/ or /_next/ files no longer fall into /[locale]/[[...page]] and won’t turn your locale into "api" or "_next".

I wanna that it helps your more.

Good luck.