-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmiddleware.ts
49 lines (41 loc) · 1.35 KB
/
middleware.ts
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
import { match } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';
import type { NextRequest } from 'next/server';
const locales = ['en', 'hi'];
function getPreferredLocale(request: NextRequest): string {
const defaultLocale = 'en';
const languages = new Negotiator({
headers: {
'accept-language': request.headers.get('Accept-Language') || '',
},
}).languages();
return match(languages, locales, defaultLocale);
}
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (pathnameHasLocale) return;
const preferredLocale = getPreferredLocale(request);
request.nextUrl.pathname = `/${preferredLocale}${pathname}`;
return Response.redirect(request.nextUrl);
}
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)
*/
{
source: '/((?!api|_next/static|_next/image|favicon.ico).*)',
missing: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
],
};