UNPKG

@pelag/nts

Version:

Creation and support of the multilingual project Next.js

40 lines (31 loc) 1.15 kB
import { NextRequest, NextResponse } from 'next/server'; import { match as matchLocale } from '@formatjs/intl-localematcher'; import Negotiator from 'negotiator'; import { langConfig } from '{{PATH}}'; function getLocale(request: NextRequest): string { const negotiatorHeaders: Record<string, string> = {}; request.headers.forEach((value, key) => { negotiatorHeaders[key] = value; }); const languages = new Negotiator({ headers: negotiatorHeaders }).languages( [...langConfig.locales] ); return matchLocale(languages, [...langConfig.locales], langConfig.defaultLocale); } export function middleware(request: NextRequest) { const { pathname } = request.nextUrl; const pathnameHasLocale = langConfig.locales.some( (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}` ); if (!pathnameHasLocale) { const locale = getLocale(request); return NextResponse.redirect( new URL(`/${locale}${pathname}`, request.url) ); } } export const config = { matcher: [ '/((?!api|_next/static|_next/image|favicon.ico|manifest.json).*)' ] };