-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
95 lines (81 loc) · 2.52 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { NextRequest, NextResponse } from 'next/server'
import acceptLanguage from 'accept-language'
import { fallbackLng, languages } from './src/app/i18n/settings'
import { getToken } from 'next-auth/jwt'
export const config = {
matcher: ['/:lng*', '/storylab/(.*)', '/login'],
}
const authRoutes = ['/storylab', '/login']
export default async function middleware(req: NextRequest) {
if (authRoutes.some(r => req.nextUrl.pathname.startsWith(r))) {
return authMiddleware(req)
}
return i18nMiddleware(req)
}
const authMiddleware = async (req: NextRequest) => {
const token = await getToken({ req })
const isAuth = !!token
const lng = getLng(req)
if (isAuth) {
if (req.nextUrl.pathname.startsWith('/login')) {
return NextResponse.redirect(new URL(`/${lng}/storylab`, req.url))
}
return NextResponse.redirect(
new URL(`/${lng}${req.nextUrl.pathname}`, req.url),
)
}
let from = req.nextUrl.pathname
if (req.nextUrl.search) {
from += req.nextUrl.search
}
if (!req.nextUrl.pathname.includes('login')) {
return NextResponse.redirect(
new URL(`/${lng}/login?from=${encodeURIComponent(from)}`, req.url),
)
}
return NextResponse.redirect(new URL(`/${lng}/login`, req.url))
}
acceptLanguage.languages(languages)
const cookieName = 'i18next'
const i18nMiddleware = (req: NextRequest) => {
if (
req.nextUrl.pathname.indexOf('icon') > -1 ||
req.nextUrl.pathname.indexOf('chrome') > -1 ||
req.nextUrl.pathname.indexOf('api') > -1 ||
req.nextUrl.pathname.indexOf('fonts') > -1
) {
return NextResponse.next()
}
const lng = getLng(req)
// Redirect if lng in path is not supported
if (
!languages.some(loc => req.nextUrl.pathname.startsWith(`/${loc}`)) &&
!req.nextUrl.pathname.startsWith('/_next')
) {
return NextResponse.redirect(
new URL(`/${lng}${req.nextUrl.pathname}`, req.url),
)
}
if (req.headers.has('referer')) {
const refererUrl = new URL(req.headers.get('referer')!)
const lngInReferer = languages.find(l =>
refererUrl.pathname.startsWith(`/${l}`),
)
const response = NextResponse.next()
if (lngInReferer) {
response.cookies.set(cookieName, lngInReferer)
}
return response
}
return NextResponse.next()
}
const getLng = (req: NextRequest): string => {
if (req.cookies.has(cookieName)) {
return acceptLanguage.get(req.cookies.get(cookieName)?.value)!
}
const header = acceptLanguage.get(req.headers.get('Accept-Language'))
if (header) {
return header
}
return fallbackLng
}