-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
34 lines (27 loc) · 909 Bytes
/
middleware.ts
File metadata and controls
34 lines (27 loc) · 909 Bytes
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
import { NextRequest, NextResponse } from 'next/server';
const PUBLIC_FILE = /\.(.*)$/;
const supportedLocales = ['en', 'ru', 'hy'];
const defaultLocale = 'en';
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Skipping public files, _next, api, etc.
if (
pathname.startsWith('/_next') ||
pathname.startsWith('/api') ||
PUBLIC_FILE.test(pathname)
) {
return;
}
// Only using browser language on "/"
if (pathname === '/') {
const acceptLang = request.headers.get('accept-language');
const preferredLocale = acceptLang
? acceptLang.split(',')[0].split('-')[0]
: defaultLocale;
const matchedLocale = supportedLocales.includes(preferredLocale)
? preferredLocale
: defaultLocale;
return NextResponse.redirect(new URL(`/${matchedLocale}`, request.url));
}
return NextResponse.next();
}