Unverified Commit deb3b023 authored by Jan Kaifer's avatar Jan Kaifer Committed by GitHub

Update i18n example to handle `public` files and `/api` routes (#45266)

> Update i18n example to handle `public` files and `/api` routes
parent 6bcb06c1
...@@ -19,23 +19,35 @@ function getLocale(request: NextRequest): string | undefined { ...@@ -19,23 +19,35 @@ function getLocale(request: NextRequest): string | undefined {
} }
export function middleware(request: NextRequest) { export function middleware(request: NextRequest) {
// Skip next internal requests const pathname = request.nextUrl.pathname
if (request.nextUrl.pathname.startsWith('/_next')) return
// // `/_next/` and `/api/` are ignored by the watcher, but we need to ignore files in `public` manually.
// // If you have one
// if (
// [
// '/manifest.json',
// '/favicon.ico',
// // Your other files in `public`
// ].includes(pathname)
// )
// return
// Check if there is any supported locale in the pathname // Check if there is any supported locale in the pathname
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = i18n.locales.every( const pathnameIsMissingLocale = i18n.locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}` (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
) )
// Let's redirect if there is no locale // Redirect if there is no locale
if (pathnameIsMissingLocale) { if (pathnameIsMissingLocale) {
const locale = getLocale(request) const locale = getLocale(request)
// e.g. incoming request is /products
// The new URL is now /en-US/products
return NextResponse.redirect(new URL(`/${locale}/${pathname}`, request.url)) return NextResponse.redirect(new URL(`/${locale}/${pathname}`, request.url))
} }
} }
export const config = { export const config = {
// We can enable redirect just from root // Matcher ignoring `/_next/` and `/api/`
// matcher: "/" matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment