I am trying to rewrite the url based on the locale retrieved from my middleware.js
, however, the url is not rewritten and returns a page-not-found 404. However, when I go to "localhost:3000/en" for example I get the correct response and everything works as expected. What am I missing here?
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);
// e.g. incoming request is /products
// The new URL is now /en/products
return NextResponse.rewrite(newUrl);
}
export const config = {
matcher: ["/((?!_next|api|favicon.ico).*)"],
};
file structure
src
-app
--[lang]
---(public)
----layout.jsx
----page.jsx
the problem appears to be having everything in my src folder. Moving my app directory into the root seems to fix the problem? Why would this be causing an issue?
If you are using the .src
folder the middleware.js
should go in the .src
folder NOT the root directory.