Skip to content

Commit deb3b02

Browse files
authored
Update i18n example to handle public files and /api routes (#45266)
> Update i18n example to handle `public` files and `/api` routes
1 parent 6bcb06c commit deb3b02

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

examples/app-dir-i18n-routing/middleware.ts

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,23 +19,35 @@ function getLocale(request: NextRequest): string | undefined {
1919
}
2020

2121
export function middleware(request: NextRequest) {
22-
// Skip next internal requests
23-
if (request.nextUrl.pathname.startsWith('/_next')) return
22+
const pathname = request.nextUrl.pathname
23+
24+
// // `/_next/` and `/api/` are ignored by the watcher, but we need to ignore files in `public` manually.
25+
// // If you have one
26+
// if (
27+
// [
28+
// '/manifest.json',
29+
// '/favicon.ico',
30+
// // Your other files in `public`
31+
// ].includes(pathname)
32+
// )
33+
// return
2434

2535
// Check if there is any supported locale in the pathname
26-
const pathname = request.nextUrl.pathname
2736
const pathnameIsMissingLocale = i18n.locales.every(
2837
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
2938
)
3039

31-
// Let's redirect if there is no locale
40+
// Redirect if there is no locale
3241
if (pathnameIsMissingLocale) {
3342
const locale = getLocale(request)
43+
44+
// e.g. incoming request is /products
45+
// The new URL is now /en-US/products
3446
return NextResponse.redirect(new URL(`/${locale}/${pathname}`, request.url))
3547
}
3648
}
3749

3850
export const config = {
39-
// We can enable redirect just from root
40-
// matcher: "/"
51+
// Matcher ignoring `/_next/` and `/api/`
52+
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
4153
}

0 commit comments

Comments
 (0)