7ff2dbb139
Build & Deploy / Build & Push Docker Image (push) Successful in 2m55s
Test / Type Check (all packages) (push) Successful in 54s
Build & Deploy / Deploy to VPS (push) Successful in 4s
Test / API Unit Tests (push) Failing after 48s
Test / Homepage Unit Tests (push) Successful in 43s
Test / Storefront Unit Tests (push) Failing after 40s
Test / Admin Unit Tests (push) Successful in 40s
Test / Dashboard Unit Tests (push) Failing after 42s
Test / API Integration Tests (push) Successful in 1m0s
48 lines
1.7 KiB
TypeScript
48 lines
1.7 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import type { NextRequest } from 'next/server'
|
|
|
|
const SHARED_LANGUAGE_COOKIE = 'rentaldrivego-language'
|
|
|
|
type Language = 'en' | 'fr' | 'ar'
|
|
|
|
function isValidLanguage(value: string | null | undefined): value is Language {
|
|
return value === 'en' || value === 'fr' || value === 'ar'
|
|
}
|
|
|
|
function detectFromAcceptLanguage(header: string | null): Language {
|
|
if (!header) return 'en'
|
|
for (const entry of header.split(',')) {
|
|
const code = entry.split(';')[0].trim().split('-')[0].toLowerCase()
|
|
if (isValidLanguage(code)) return code
|
|
}
|
|
return 'en'
|
|
}
|
|
|
|
export function proxy(request: NextRequest) {
|
|
if (request.headers.has('x-middleware-subrequest')) {
|
|
return new NextResponse('Unsupported internal request header', { status: 400 })
|
|
}
|
|
|
|
const currentLanguage = request.cookies.get(SHARED_LANGUAGE_COOKIE)?.value
|
|
if (isValidLanguage(currentLanguage)) return NextResponse.next()
|
|
|
|
const language = detectFromAcceptLanguage(request.headers.get('accept-language'))
|
|
const requestHeaders = new Headers(request.headers)
|
|
const existingCookies = request.headers.get('cookie') ?? ''
|
|
const languageCookie = `${SHARED_LANGUAGE_COOKIE}=${language}`
|
|
requestHeaders.set('cookie', existingCookies ? `${existingCookies}; ${languageCookie}` : languageCookie)
|
|
|
|
const response = NextResponse.next({ request: { headers: requestHeaders } })
|
|
response.cookies.set(SHARED_LANGUAGE_COOKIE, language, {
|
|
maxAge: 365 * 24 * 60 * 60,
|
|
path: '/',
|
|
sameSite: 'lax',
|
|
secure: process.env.NODE_ENV === 'production',
|
|
})
|
|
return response
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/((?!_next/static|_next/image|_next/webpack-hmr|favicon\\.ico|.*\\.(?:png|ico|jpg|jpeg|svg|webp)$).*)'],
|
|
}
|