Next.js Discord

Discord Forum

internationalization routing

Unanswered
KenTay posted this in #help-forum
Open in Discord
Why is my middleware not routing properly ? When I go to / page it does not add the locale in the url but page shows, but if i go to /fr page it triggers a not found. My middleware and my folder architecture below
import { NextRequest, NextResponse } from 'next/server'
import { match } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';

let locales = ['fr', 'en'];

export let defaultLocale = 'fr';

function getLocale(request: Request): string {
    const headers = new Headers(request.headers)
    const acceptLanguage = headers.get("accept-language")
    if (acceptLanguage) {
        headers.set('accept-language', acceptLanguage.replaceAll("_", "-"))
    }

    const headersObject = Object.fromEntries(headers.entries());
    const languages = new Negotiator({ headers: headersObject }).languages();
    return match(languages, locales, defaultLocale);
}

export function middleware(request: NextRequest) {
    let locale = getLocale(request) ?? defaultLocale

    const pathname = request.nextUrl.pathname
    console.log("pathname", pathname);
    console.log("new url", `/${locale}${pathname}`);
    console.log("next url", request.nextUrl);


    const newUrl = new URL(`/${locale}${pathname}`, request.nextUrl);

    // // e.g. incoming request is /products
    // // The new URL is now /en/products
    return NextResponse.rewrite(newUrl)
}

export const config = {
    matcher: [
        // Skip all internal paths (_next)
        '/((?!_next|api|favicon.ico).*)',
        // Optional: only run on root (/) URL
        // '/'
    ],
}

0 Replies