site/middleware.ts
Dariusz Niemczyk 277300a68b
WIP
2025-01-29 18:44:39 +01:00

32 lines
980 B
TypeScript

import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
const locales = ["en", "pl"];
const defaultLocale = "pl";
function getLocale(request: NextRequest) {
const headers = {
"accept-language": request.headers.get("accept-language") || "",
};
const languages = new Negotiator({ headers }).languages();
return match(languages, locales, defaultLocale);
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
const pathnameIsMissingLocale = locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
);
if (pathnameIsMissingLocale) {
const locale = getLocale(request);
return NextResponse.redirect(new URL(`/${locale}${pathname}`, request.url));
}
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};