feat: enable browser language detection for locale routing
- Root / now uses next-intl locale detection to redirect based on Accept-Language header (English browser → /en, Serbian → /sr, etc.) - Old Serbian URLs (/products, /about, etc.) still redirect to /sr/* with 301 - English URLs (/en/*) remain unchanged
This commit is contained in:
@@ -3,37 +3,43 @@ import { NextResponse } from "next/server";
|
|||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
import { routing } from "./src/i18n/routing";
|
import { routing } from "./src/i18n/routing";
|
||||||
|
|
||||||
const oldSerbianPaths = ["", "products", "about", "contact", "checkout"];
|
|
||||||
|
|
||||||
export default function middleware(request: NextRequest) {
|
export default function middleware(request: NextRequest) {
|
||||||
const pathname = request.nextUrl.pathname;
|
const pathname = request.nextUrl.pathname;
|
||||||
|
|
||||||
const isOldSerbianPath = oldSerbianPaths.some((path) => {
|
|
||||||
if (path === "") {
|
|
||||||
return pathname === "/";
|
|
||||||
}
|
|
||||||
return pathname === `/${path}` || pathname.startsWith(`/${path}/`);
|
|
||||||
});
|
|
||||||
|
|
||||||
const hasLocalePrefix = routing.locales.some(
|
const hasLocalePrefix = routing.locales.some(
|
||||||
(locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`)
|
(locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`)
|
||||||
);
|
);
|
||||||
|
|
||||||
if (isOldSerbianPath && !hasLocalePrefix) {
|
if (hasLocalePrefix) {
|
||||||
const newPathname = pathname === "/"
|
const intlMiddleware = createMiddleware({
|
||||||
? "/sr"
|
...routing,
|
||||||
: `/sr${pathname}`;
|
});
|
||||||
|
return intlMiddleware(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pathname === "/" || pathname === "") {
|
||||||
|
const intlMiddleware = createMiddleware({
|
||||||
|
...routing,
|
||||||
|
localeDetection: true,
|
||||||
|
});
|
||||||
|
return intlMiddleware(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldSerbianPaths = ["products", "about", "contact", "checkout"];
|
||||||
|
const isOldSerbianPath = oldSerbianPaths.some(
|
||||||
|
(path) => pathname === `/${path}` || pathname.startsWith(`/${path}/`)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isOldSerbianPath) {
|
||||||
|
const newPathname = `/sr${pathname}`;
|
||||||
const url = request.nextUrl.clone();
|
const url = request.nextUrl.clone();
|
||||||
url.pathname = newPathname;
|
url.pathname = newPathname;
|
||||||
|
|
||||||
return NextResponse.redirect(url, 301);
|
return NextResponse.redirect(url, 301);
|
||||||
}
|
}
|
||||||
|
|
||||||
const intlMiddleware = createMiddleware({
|
const intlMiddleware = createMiddleware({
|
||||||
...routing,
|
...routing,
|
||||||
});
|
});
|
||||||
|
|
||||||
return intlMiddleware(request);
|
return intlMiddleware(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user