|
| 1 | +import { match as matchLocale } from '@formatjs/intl-localematcher' |
| 2 | +import Negotiator from 'negotiator' |
| 3 | +import { NextResponse } from 'next/server' |
| 4 | +import type { NextRequest } from 'next/server' |
| 5 | + |
| 6 | +const locales = JSON.parse(process.env.NEXTRA_LOCALES!) as string[] |
| 7 | + |
| 8 | +const defaultLocale = process.env.NEXTRA_DEFAULT_LOCALE! |
| 9 | + |
| 10 | +const HAS_LOCALE_RE = new RegExp(`^\\/(${locales.join('|')})(\\/|$)`) |
| 11 | + |
| 12 | +const COOKIE_NAME = 'NEXT_LOCALE' |
| 13 | + |
| 14 | +function getHeadersLocale(request: NextRequest): string { |
| 15 | + const headers = Object.fromEntries( |
| 16 | + // @ts-expect-error -- this works |
| 17 | + request.headers.entries() |
| 18 | + ) |
| 19 | + |
| 20 | + // Use negotiator and intl-localematcher to get best locale |
| 21 | + const languages = new Negotiator({ headers }).languages(locales) |
| 22 | + const locale = matchLocale(languages, locales, defaultLocale) |
| 23 | + |
| 24 | + return locale |
| 25 | +} |
| 26 | + |
| 27 | +export function middleware(request: NextRequest) { |
| 28 | + const { pathname } = request.nextUrl |
| 29 | + |
| 30 | + // Check if there is any supported locale in the pathname |
| 31 | + const pathnameHasLocale = HAS_LOCALE_RE.test(pathname) |
| 32 | + const cookieLocale = request.cookies.get(COOKIE_NAME)?.value |
| 33 | + |
| 34 | + // Redirect if there is no locale |
| 35 | + if (!pathnameHasLocale) { |
| 36 | + const locale = cookieLocale || getHeadersLocale(request) |
| 37 | + |
| 38 | + // e.g. incoming request is /products |
| 39 | + // The new URL is now /en-US/products |
| 40 | + return NextResponse.redirect(new URL(`/${locale}${pathname}`, request.url)) |
| 41 | + } |
| 42 | + |
| 43 | + const requestLocale = pathname.split('/', 2)[1] |
| 44 | + |
| 45 | + if (requestLocale !== cookieLocale) { |
| 46 | + const response = NextResponse.next() |
| 47 | + response.cookies.set(COOKIE_NAME, requestLocale) |
| 48 | + return response |
| 49 | + } |
| 50 | +} |
0 commit comments