|
| 1 | +import { NextRequest, NextResponse } from "next/server" |
| 2 | + |
| 3 | +import { DEFAULT_LOCALE, FAKE_LOCALE, LOCALES_CODES } from "./lib/constants" |
| 4 | + |
| 5 | +const PUBLIC_FILE = /\.(.*)$/ |
| 6 | + |
| 7 | +function detectLocale(acceptLanguage: string | null) { |
| 8 | + if (!acceptLanguage) { |
| 9 | + return DEFAULT_LOCALE |
| 10 | + } |
| 11 | + |
| 12 | + // it comes in the format of `en-US,en;q=0.9,de;q=0.8` |
| 13 | + const locales = acceptLanguage.split(",") |
| 14 | + |
| 15 | + const locale = locales |
| 16 | + .map((localeWeight) => localeWeight.split(";")[0].trim()) |
| 17 | + .find((locale) => { |
| 18 | + return LOCALES_CODES.includes(locale) |
| 19 | + }) |
| 20 | + |
| 21 | + return locale |
| 22 | +} |
| 23 | + |
| 24 | +export const config = { |
| 25 | + matcher: [ |
| 26 | + "/", // explicit matcher for root route |
| 27 | + /* |
| 28 | + * Match all request paths except for the ones starting with: |
| 29 | + * - _next/static (static files) |
| 30 | + */ |
| 31 | + "/((?!_next/static).*)", |
| 32 | + ], |
| 33 | +} |
| 34 | + |
| 35 | +// Middleware required to always display the locale prefix in the URL. It |
| 36 | +// redirects to the default locale if the locale is not present in the URL |
| 37 | +export async function middleware(req: NextRequest) { |
| 38 | + const { pathname, locale, search } = req.nextUrl |
| 39 | + |
| 40 | + if ( |
| 41 | + pathname.startsWith("/_next") || |
| 42 | + pathname.includes("/api/") || |
| 43 | + PUBLIC_FILE.test(pathname) |
| 44 | + ) { |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + if (locale === FAKE_LOCALE) { |
| 49 | + // Apparently, the built-in `localeDetection`from Next does not work when |
| 50 | + // using the faked locale hack. So, we need to detect the locale manually |
| 51 | + const localeDetected = detectLocale(req.headers.get("accept-language")) |
| 52 | + const locale = localeDetected || DEFAULT_LOCALE |
| 53 | + |
| 54 | + const redirectUrl = new URL(`/${locale}${pathname}${search}`, req.url) |
| 55 | + |
| 56 | + // Add trailing slash if it's not present |
| 57 | + if (!redirectUrl.pathname.endsWith("/")) { |
| 58 | + redirectUrl.pathname = redirectUrl.pathname + "/" |
| 59 | + } |
| 60 | + |
| 61 | + return NextResponse.redirect(redirectUrl, { status: 301 }) |
| 62 | + } |
| 63 | +} |
0 commit comments