I've been attempting to rewrite the URL based on the locale extracted from my middleware.js
, but for some reason, the URL isn't being rewritten and leads to a page-not-found error 404. Strangely though, if I manually navigate to "localhost:3000/en" for instance, everything works smoothly as expected. Any idea what could be causing this discrepancy?
middleware.js
import { NextResponse } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
let locales = ["en", "ka", "ru"];
export let defaultLocale = "en";
function getLocale(request) {
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) {
let locale = getLocale(request) ?? defaultLocale;
const pathname = request.nextUrl.pathname;
const newUrl = new URL(`/${locale}${pathname}`, request.nextUrl);
// For example, if the incoming request is /products
// The new URL should now be /en/products
return NextResponse.rewrite(newUrl);
}
export const config = {
matcher: ["/((?!_next|api|favicon.ico).*)"],
};
file structure
src
-app
--[lang]
---(public)
----layout.jsx
----page.jsx
UPDATE
Upon investigation, it seems that having all my files in the src folder is causing the issue. Moving the app directory to the root directory resolves the problem. Why would this relocation be causing an error?