-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathproxy.ts
More file actions
66 lines (57 loc) · 2.07 KB
/
proxy.ts
File metadata and controls
66 lines (57 loc) · 2.07 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
60
61
62
63
64
65
66
import createMiddleware from 'next-intl/middleware';
import { NextRequest, NextResponse } from 'next/server';
import { routing } from './core/i18n/routing';
import {
getCanonicalNoPrefixPath,
hasLocalePrefix,
isTranslatorPath,
} from './shared/lib/translator-routing';
// Create intl middleware once at module level (more efficient)
const intlMiddleware = createMiddleware(routing);
const translatorMiddleware = createMiddleware({
...routing,
localeDetection: false,
alternateLinks: false,
});
export default function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// Fast path - skip for paths that don't need locale handling
if (
pathname.startsWith('/_next') ||
pathname.startsWith('/api') ||
pathname.startsWith('/_vercel') ||
pathname.startsWith('/monitoring') ||
pathname.startsWith('/healthcheck') ||
pathname.includes('.')
) {
return NextResponse.next();
}
if (hasLocalePrefix(pathname)) {
const redirectUrl = request.nextUrl.clone();
redirectUrl.pathname = getCanonicalNoPrefixPath(pathname);
return NextResponse.redirect(redirectUrl, 308);
}
if (isTranslatorPath(pathname)) {
const response = translatorMiddleware(request);
response.headers.set('x-locale', 'en');
return response;
}
// Locale prefix is disabled; derive locale from cookie, then Accept-Language.
const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value;
const acceptLanguage = request.headers.get('accept-language') ?? '';
const preferredLocale = acceptLanguage.toLowerCase().startsWith('es')
? 'es'
: 'en';
const locale = cookieLocale === 'es' || cookieLocale === 'en'
? cookieLocale
: preferredLocale;
// Use next-intl middleware for locale handling
const response = intlMiddleware(request);
response.headers.set('x-locale', locale);
return response;
}
export const config = {
// More restrictive matcher - only match actual page routes
// Excludes: api, _next, _vercel, static files, and common bot endpoints
matcher: ['/((?!api|_next|_vercel|monitoring|healthcheck|.*\\..*).*)'],
};