From ca2a1a8f889eaf16e83e8e8b710f414096725bf1 Mon Sep 17 00:00:00 2001 From: Guillermo Pages Date: Wed, 5 Nov 2025 22:19:39 +0100 Subject: [PATCH] fix(middleware): handle invalid locale values in Accept-Language header Added error handling to prevent middleware crashes when browsers send invalid locale codes. Filters out malformed locale values before passing to Intl.getCanonicalLocales, with fallback to default locale if all values are invalid. Fixes: RangeError: Incorrect locale information provided --- src/middleware.ts | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/middleware.ts b/src/middleware.ts index 49667d6..60d5455 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -14,8 +14,28 @@ function getLocale(request: NextRequest): string { negotiatorHeaders[key] = value; }); - const languages = new Negotiator({ headers: negotiatorHeaders }).languages(); - return match(languages, i18n.locales, i18n.defaultLocale); + try { + const languages = new Negotiator({ headers: negotiatorHeaders }).languages(); + // Filter out invalid locale values that would cause Intl.getCanonicalLocales to fail + const validLanguages = languages.filter((lang) => { + try { + Intl.getCanonicalLocales(lang); + return true; + } catch { + return false; + } + }); + + if (validLanguages.length === 0) { + return i18n.defaultLocale; + } + + return match(validLanguages, i18n.locales, i18n.defaultLocale); + } catch (error) { + // Fallback to default locale if locale negotiation fails + console.error('Locale negotiation error:', error); + return i18n.defaultLocale; + } } export function middleware(request: NextRequest) {