Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | import { NextRequest, NextResponse } from "next/server"; import { sessionCookieName } from "./appConstants"; import { allLanguages } from "./i18n/allLanguages"; function getBrowserLocale( acceptLanguage: string | undefined, ): string | undefined { Iif (!acceptLanguage) return undefined; // Parse Accept-Language header const languages = acceptLanguage .split(",") .map((lang) => { const [code, quality = "1"] = lang.trim().split(";q="); return { code: code.split("-")[0], quality: parseFloat(quality) }; }) .sort((a, b) => b.quality - a.quality); // Find the first supported language for (const lang of languages) { const supportedLang = allLanguages.find((supported) => supported.startsWith(lang.code), ); Iif (supportedLang) { return supportedLang; } } return undefined; } export function middleware(request: NextRequest) { Iif ( request.cookies.get(sessionCookieName) && request.nextUrl.pathname === "/" ) { const url = request.nextUrl.clone(); url.pathname = "/dashboard"; return NextResponse.rewrite(url); } const response = NextResponse.next(); // Check if NEXT_LOCALE cookie exists and is valid const cookieLocale = request.cookies.get("NEXT_LOCALE")?.value; // Only set cookie if it doesn't exist OR if it exists but is not a valid language Iif (!cookieLocale || !allLanguages.includes(cookieLocale)) { // No valid cookie exists, detect browser language and set cookie const browserLocale = getBrowserLocale( request.headers.get("accept-language") || undefined, ); const detectedLocale = browserLocale && allLanguages.includes(browserLocale) ? browserLocale : "en"; // Set the NEXT_LOCALE cookie response.cookies.set("NEXT_LOCALE", detectedLocale, { path: "/", maxAge: 31536000, // 1 year sameSite: "lax", }); } return response; } export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) */ "/((?!api|_next/static|_next/image|favicon.ico).*)", ], }; |