forked from Bithomp/frontend-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
53 lines (43 loc) · 1.67 KB
/
middleware.js
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
import { NextResponse } from 'next/server'
const PUBLIC_FILE = /\.(.*)$/
export async function middleware(req) {
if (
req.nextUrl.pathname.startsWith('/_next') ||
req.nextUrl.pathname.includes('/api/') ||
PUBLIC_FILE.test(req.nextUrl.pathname)
) {
return
}
const cookieLocale = req.cookies.get('NEXT_LOCALE')?.value
//if someone has an old link with old locale that was removed.
const removedLocales = ['ca', 'da', 'nn', 'my', 'hr']
const currentLocales = ['en', 'ko', 'ru', 'de', 'es', 'id', 'ja']
const reactLocale = req.nextUrl.locale
//default option
let viewLocale = 'en'
if (currentLocales.includes(reactLocale)) {
// exlude 'default' locale
viewLocale = reactLocale
}
// if the cookie locale is set and is one of the currently supported locales - then it's a priority
if (cookieLocale && currentLocales.includes(cookieLocale)) {
viewLocale = cookieLocale
}
//if locale is one of the deleted ones
for (const locale of removedLocales) {
if (req.nextUrl.pathname.startsWith(`/${locale}/` && locale !== viewLocale)) {
return NextResponse.redirect(
new URL(`${req.nextUrl.pathname.replace(`/${locale}/`, `/${viewLocale}/`)}${req.nextUrl.search}`, req.url)
)
}
if (req.nextUrl.pathname === `/${locale}` && locale !== viewLocale) {
return NextResponse.redirect(
new URL(`${req.nextUrl.pathname.replace(`/${locale}`, `/${viewLocale}`)}${req.nextUrl.search}`, req.url)
)
}
}
//import to have this case: reactLocale === 'default'
if (reactLocale !== viewLocale) {
return NextResponse.redirect(new URL(`/${viewLocale}${req.nextUrl.pathname}${req.nextUrl.search}`, req.url))
}
}