Files
website/src/middleware.ts
T

59 lines
1.8 KiB
TypeScript

import createMiddleware from 'next-intl/middleware'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { defaultLocale, locales } from './i18n/config'
import { getSiteUrl } from './lib/seo'
const intlMiddleware = createMiddleware({
locales: [...locales],
defaultLocale,
localePrefix: 'always',
localeDetection: false,
})
function shouldUseSimplifiedChinese(request: NextRequest) {
const acceptLanguage = request.headers.get('accept-language') || ''
const firstLanguage = acceptLanguage
.split(',')
.map((part) => part.trim().split(';')[0]?.toLowerCase())
.find(Boolean)
return Boolean(
firstLanguage &&
(firstLanguage === 'zh-cn' ||
firstLanguage === 'zh-hans' ||
firstLanguage === 'zh-sg' ||
firstLanguage.startsWith('zh-hans-')),
)
}
export default function middleware(request: NextRequest) {
const { pathname, search } = request.nextUrl
if (pathname === '/admin/forgot' || pathname.startsWith('/admin/forgot/')) {
return new NextResponse(null, { status: 404 })
}
const hasLocalePrefix = locales.some(
(locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`),
)
if (!hasLocalePrefix) {
const locale = shouldUseSimplifiedChinese(request) ? 'zh' : 'en'
const url = new URL(request.nextUrl.pathname, getSiteUrl())
url.pathname = `/${locale}${pathname === '/' ? '' : pathname}`
url.search = search
return NextResponse.redirect(url)
}
return intlMiddleware(request)
}
export const config = {
matcher: [
'/admin/forgot/:path*',
// Skip all internal paths (_next, _vercel, api, admin, payload assets, static files)
'/((?!api|admin|_next|_vercel|favicon\\.ico|robots\\.txt|sitemap.*|Products|Product|.*\\..*).*)',
],
}