@wezom/locale-handler
v1.0.6
Published
Locale handler for middleware with redirects
Downloads
12
Maintainers
Readme
@wezom/locale-handler
Locale handler for middleware with redirects
Code coverage:
| Statements | Branches | Functions | Lines | | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | | | | |
Installation
Via pnpm:
pnpm add @wezom/locale-handler
Via npm:
npm install @wezom/locale-handler
Via yarn:
yarn add @wezom/locale-handler
Usage example with Next.js App Route
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).*)'],
};