Next.js Discord

Discord Forum

Middleware interferes with not-found page

Answered
JChicano posted this in #help-forum
Open in Discord
This is my middleware, that handle a page in various languages
import { NextRequest, NextResponse } from "next/server";

const locales = ['en', 'es'];

function getLocale(request: any): string {
  const acceptLanguage = request.headers.get('accept-language');

  if (!acceptLanguage) return locales[0];

  const acceptedLocales = acceptLanguage.split(',').map((lang: string) => lang.split(';')[0].trim());
  for (const locale of acceptedLocales) {
    if (locales.includes(locale)) {
      return locale;
    }
  }

  return locales[0];
}

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  const pathnameHasLocale = locales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
  );

  if (pathnameHasLocale) return

  const locale = getLocale(request);

  request.nextUrl.pathname = `/${locale}${pathname}`;
  return NextResponse.redirect(request.nextUrl);
}

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

The problem is that when i enter an invalid URL that doesnt exits, it throws this error, bcs next doesnt find the not-found page
Answered by joulev
yeah you need to add <html> and <body> to this not-found.tsx
View full answer

15 Replies

yes it's this estructure, the problem is that the middleware handle every route that contains "/en" or "/es/" and when i enter "/en/SomeRoute" obviously there is not a page for this, and the not-found doesnt appear
yes yes
is it inside [locale] or outside
like that
outside
@JChicano like that
yeah you need to add <html> and <body> to this not-found.tsx
Answer
because the layout.tsx inside [locale] does not wrap this not-found.tsx, the not-found.tsx does not have any wrapping <html> and <body> so you need to provide these tags
yeee, you are right
ty, now its working
nice!
ty very much omg
😄
you're welcome