From 8244ba161ba6148c00c0599016c167f0492bdcbe Mon Sep 17 00:00:00 2001 From: Unchained Date: Tue, 24 Mar 2026 07:42:18 +0200 Subject: [PATCH] feat: enable browser language detection for locale routing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- middleware.ts | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/middleware.ts b/middleware.ts index d09705a..d7b7270 100644 --- a/middleware.ts +++ b/middleware.ts @@ -3,37 +3,43 @@ import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { routing } from "./src/i18n/routing"; -const oldSerbianPaths = ["", "products", "about", "contact", "checkout"]; - export default function middleware(request: NextRequest) { 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( (locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`) ); - if (isOldSerbianPath && !hasLocalePrefix) { - const newPathname = pathname === "/" - ? "/sr" - : `/sr${pathname}`; - + if (hasLocalePrefix) { + const intlMiddleware = createMiddleware({ + ...routing, + }); + 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(); url.pathname = newPathname; - return NextResponse.redirect(url, 301); } const intlMiddleware = createMiddleware({ ...routing, }); - return intlMiddleware(request); }