AWSCLOUD/middleware.ts

44 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

2025-09-16 15:24:39 +08:00
import { NextRequest, NextResponse } from 'next/server';
import acceptLanguage from 'accept-language';
const supportedLangs = ['en', 'zh-CN', 'zh-TW', 'ko', 'ja'];
const defaultLang = 'en';
acceptLanguage.languages(supportedLangs);
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)
* - sitemap.xml (sitemap file)
* - robots.txt (robots file)
*/
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)'
]
};
export function middleware(req: NextRequest) {
const pathname = req.nextUrl.pathname;
// Check if there is any supported locale in the pathname
const pathnameIsMissingLocale = supportedLangs.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
);
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
const locale = acceptLanguage.get(req.headers.get('Accept-Language')) || defaultLang;
// e.g. incoming request is /products
// The new URL is now /en/products
return NextResponse.redirect(
new URL(`/${locale}${pathname.startsWith('/') ? '' : '/'}${pathname}`, req.url)
);
}
return NextResponse.next();
}