-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
36 lines (26 loc) · 1.17 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import i18n from '@i18next';
export function middleware(request: NextRequest) {
const locales = i18n.options.supportedLngs as string[];
const defaultLang = (i18n.options.fallbackLng as string[])[0];
const { headers, nextUrl } = request;
// Exclude statics - add your static folders
const shouldCheckLocale = !nextUrl.pathname.startsWith('/_next') && !nextUrl.pathname.startsWith('/favicon');
// && !nextUrl.pathname.startsWith("/images/");
const reqLocale = nextUrl.pathname.split('/')[1];
const noValidLocale = !locales.includes(reqLocale);
if (shouldCheckLocale && noValidLocale) {
// TODO: check from cookie before detecting
const accepts = headers.get('accept-language') || '';
// Omit country for now
const detected = accepts.split(',')[0].split('-')[0];
const validLocale = locales.includes(detected) ? detected : defaultLang;
nextUrl.pathname = `${nextUrl.pathname}`;
return NextResponse.rewrite(new URL(`/${validLocale}${nextUrl.pathname}`, request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/:path*'],
};