-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
74 lines (60 loc) · 2.46 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
import { NextRequest, NextResponse } from 'next/server'
import { defaultLocale, localeCookieName } from '@/config/localization'
import { createManagmentHeaders } from '@/config/contentstack/managementSDK'
import { isLocale } from '@/utils/localization'
import { Locale } from './types/common'
const fetchLocales = async () => {
const requestOptions = createManagmentHeaders('GET')
const res = await fetch(`https://${process.env.CONTENTSTACK_API_HOST}/v3/locales`, requestOptions)
const {locales} = await res.json()
return locales?.length > 0 ? locales?.map((locale: Locale) => ({
code: locale.code,
name: locale.name,
fallback_locale: locale.fallback_locale
})) : []
}
export async function middleware (request: NextRequest) {
const pathname = request.nextUrl.pathname
const languagesCookie = request.cookies.get(localeCookieName)
const locales = languagesCookie?.value ? JSON.parse(languagesCookie.value) : await fetchLocales()
const pathnameHasLocale = pathname.split('/')?.some((p) => {
return isLocale(p)
})
if (pathnameHasLocale) {
try {
const response = NextResponse.next()
if (!languagesCookie) {
// set "languages" cookie in res.cookie - if cookie not exist
// cookie will expire in 5 days
response.cookies.set(localeCookieName, JSON.stringify(locales), {
expires: new Date(Date.now() + ( 5 * 24 * 60 * 60 * 1000)),
sameSite: 'none',
secure: true
})
return response
} // if request.cookie exist then return
return response
} catch(err) {
console.error('Error while parsing locale : ', err)
NextResponse.next()
}
}
// Redirect to default locale if there is no locale in url
request.nextUrl.pathname = `/${defaultLocale}${pathname}`
return NextResponse.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)
* - robots.txt (robots file)
*/
'/((?!api|_next/static|_next/image|favicon.ico|robots.txt).*)',
// allow / routes
'/'
]
}