-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
49 lines (42 loc) · 1.51 KB
/
Copy pathproxy.ts
File metadata and controls
49 lines (42 loc) · 1.51 KB
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
import { proxy as nextraLocaleProxy } from 'nextra/locales'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import localeRoutes from './locale-routes.json'
const englishRoutes = new Set(localeRoutes.en)
const localizedRoutes = new Map<string, Set<string>>(
Object.entries(localeRoutes)
.filter(([locale]) => locale !== 'en')
.map(([locale, routes]) => [locale, new Set(routes)])
)
export function proxy(request: NextRequest) {
const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value
if (cookieLocale && !Object.hasOwn(localeRoutes, cookieLocale)) {
// Nextra uses this value in a redirect URL; only supported locale names are safe.
request.cookies.delete('NEXT_LOCALE')
}
const [locale = '', ...routeSegments] = request.nextUrl.pathname
.split('/')
.filter(Boolean)
const localizedRoute = routeSegments.join('/')
const availableRoutes = localizedRoutes.get(locale)
if (
availableRoutes &&
englishRoutes.has(localizedRoute) &&
!availableRoutes.has(localizedRoute)
) {
const url = request.nextUrl.clone()
url.pathname = `/${locale}`
url.search = ''
const response = NextResponse.redirect(url)
response.cookies.set('NEXT_LOCALE', locale)
return response
}
return nextraLocaleProxy(request)
}
export const config = {
// Matcher ignoring `/_next/` and `/api/`
matcher: [
// Ignore /api, /_next, /_pagefind, and any path with a file extension (e.g. /logo.png)
'/((?!api|_next|_pagefind|.*\\..*).*)'
]
}