fix(middleware): handle invalid locale values in Accept-Language header
continuous-integration/drone/push Build is passing Details

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
master
Guillermo Pages 1 month ago
parent 26a1975799
commit ca2a1a8f88

@ -14,8 +14,28 @@ function getLocale(request: NextRequest): string {
negotiatorHeaders[key] = value; negotiatorHeaders[key] = value;
}); });
try {
const languages = new Negotiator({ headers: negotiatorHeaders }).languages(); const languages = new Negotiator({ headers: negotiatorHeaders }).languages();
return match(languages, i18n.locales, i18n.defaultLocale); // 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) { export function middleware(request: NextRequest) {

Loading…
Cancel
Save