Locale handler for middleware with redirects
Code coverage:
Statements | Branches | Functions | Lines |
---|---|---|---|
Via pnpm:
pnpm add @wezom/locale-handler
Via npm:
npm install @wezom/locale-handler
Via yarn:
yarn add @wezom/locale-handler
According to Next.js documentation about Internationalization, you can create a own middleware to handle missing locales redirects.
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { LocaleHandler } from '@wezom/locale-handler';
export function middleware(request: NextRequest): void | NextResponse {
const localeHandler = new LocaleHandler({
acceptLanguages: request.headers.get('accept-language'),
availableLocales: ['uk', 'en'],
defaultLocale: 'uk',
url: request.nextUrl,
});
if (localeHandler.pathnameHasMissingLocale) {
const url = localeHandler.getPreferredLocaleUrl();
return NextResponse.redirect(url);
}
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};