forked from lingdojo/kana-dojo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
44 lines (37 loc) · 1.49 KB
/
middleware.ts
File metadata and controls
44 lines (37 loc) · 1.49 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
import createMiddleware from 'next-intl/middleware';
import { NextRequest, NextResponse } from 'next/server';
import { routing } from './core/i18n/routing';
// Create intl middleware once at module level (more efficient)
const intlMiddleware = createMiddleware(routing);
export default function middleware(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();
}
// 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|.*\\..*).*)'],
};