1.0.6 • Published 9 months ago

@wezom/locale-handler v1.0.6

Weekly downloads
-
License
BSD 3-Clause Lice...
Repository
-
Last release
9 months ago

@wezom/locale-handler

Locale handler for middleware with redirects

Code coverage:

StatementsBranchesFunctionsLines
StatementsBranchesFunctionsLines

GitHub Actions:
CI Test and Build


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).*)'],
};