forked from sleepypod/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
48 lines (37 loc) · 1.57 KB
/
proxy.ts
File metadata and controls
48 lines (37 loc) · 1.57 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
import linguiConfig from 'lingui.config'
import Negotiator from 'negotiator'
import { type NextRequest, NextResponse } from 'next/server'
const { locales } = linguiConfig
const getRequestLocale = (requestHeaders: Headers): string => {
const langHeader = requestHeaders.get('accept-language') || undefined
const languages = new Negotiator({
headers: { 'accept-language': langHeader },
}).languages(locales.slice())
// Ensure the locale is valid, default to the first locale in `linguiConfig.locales`
const activeLocale = languages.find(lang => locales.includes(lang)) || locales[0] || 'en'
return activeLocale
}
export const proxy = (request: NextRequest) => {
const { pathname } = request.nextUrl
console.log('Current pathname:', pathname)
const pathnameHasLocale = locales.some(
(locale: string) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`,
)
console.log('Pathname has locale:', pathnameHasLocale)
if (pathnameHasLocale) {
return
}
// Redirect if there is no locale
const locale = getRequestLocale(request.headers)
console.log('Redirecting to locale:', locale) // Debugging: Log the locale being redirected to
request.nextUrl.pathname = `/${locale}${pathname}`
return NextResponse.redirect(request.nextUrl)
}
// Routes excluded from locale redirect:
// api — tRPC + REST endpoints, no locale needed
// panel — tRPC panel dev tool, served as a plain route handler
export const config = {
matcher: [
'/((?!api|panel(?:/|$)|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
}