-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmiddleware.ts
More file actions
59 lines (50 loc) · 1.83 KB
/
Copy pathmiddleware.ts
File metadata and controls
59 lines (50 loc) · 1.83 KB
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
import { NextRequest, NextResponse } from "next/server";
import { LANGUAGE_STORAGE_KEY, SUPPORTED_LANGUAGES } from "@/src/constants";
import { detectLanguageFromHeader, isRedirectExcludedUrl } from "@/src/hooks/i18n/serverUtils";
/**
* Middleware to handle server-side language detection and redirection
* This runs on every request before the page is rendered
*/
export function middleware(request: NextRequest) {
// Get current URL and pathname
const url = request.nextUrl.clone();
const { pathname } = url;
// Skip redirects for excluded URLs
if (isRedirectExcludedUrl(pathname)) {
return NextResponse.next();
}
// Check if user has a language preference in cookies
const cookieLanguage = request.cookies.get(LANGUAGE_STORAGE_KEY)?.value;
// Check if user's preferred language is already set in cookies
if (cookieLanguage && SUPPORTED_LANGUAGES.includes(cookieLanguage as any)) {
// User has a valid language preference, no need to redirect
return NextResponse.next();
}
// Detect preferred language from Accept-Language header
const detectedLanguage = detectLanguageFromHeader(request);
// Create response to set cookie with detected language
const response = NextResponse.next();
// Set cookie with the detected language
response.cookies.set(LANGUAGE_STORAGE_KEY, detectedLanguage, {
maxAge: 60 * 60 * 24 * 365, // 1 year
path: "/",
});
return response;
}
/**
* Configure the middleware to run on specific paths
*/
export const config = {
// Match all request paths except for excluded paths
matcher: [
/*
* Match all paths except for:
* 1. /api routes
* 2. /_next (Next.js internals)
* 3. /static (static files)
* 4. /locales (translation files)
* 5. all files in the public folder
*/
"/((?!api|_next|static|locales|favicon.ico|robots.txt).*)",
],
};