Unverified Commit fcca4ce9 authored by GabenGar's avatar GabenGar Committed by GitHub

fix(docs): internationalization middleware example (#55645)

- remove the slash before `pathname` (already included in the value).
- add `search` and `hash` values in redirected url:
   - retains these values on redirect
   - they already have `?` and `#` respectively
Co-authored-by: 's avatarBalázs Orbán <18369201+balazsorban44@users.noreply.github.com>
parent ac1c062f
...@@ -33,30 +33,27 @@ match(languages, locales, defaultLocale) // -> 'en-US' ...@@ -33,30 +33,27 @@ match(languages, locales, defaultLocale) // -> 'en-US'
Routing can be internationalized by either the sub-path (`/fr/products`) or domain (`my-site.fr/products`). With this information, you can now redirect the user based on the locale inside [Middleware](/docs/app/building-your-application/routing/middleware). Routing can be internationalized by either the sub-path (`/fr/products`) or domain (`my-site.fr/products`). With this information, you can now redirect the user based on the locale inside [Middleware](/docs/app/building-your-application/routing/middleware).
```js filename="middleware.js" ```js filename="middleware.js"
import { NextResponse } from 'next/server'
let locales = ['en-US', 'nl-NL', 'nl'] let locales = ['en-US', 'nl-NL', 'nl']
// Get the preferred locale, similar to above or using a library // Get the preferred locale, similar to the above or using a library
function getLocale(request) { ... } function getLocale(request) { ... }
export function middleware(request) { export function middleware(request) {
// 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 { pathname } = request.nextUrl
const pathnameIsMissingLocale = locales.every( const pathnameHasLocale = locales.some(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}` (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
) )
if (pathnameHasLocale) return
// Redirect if there is no locale // Redirect if there is no locale
if (pathnameIsMissingLocale) { const locale = getLocale(request)
const locale = getLocale(request) request.nextUrl.pathname = `/${locale}${pathname}`
// e.g. incoming request is /products
// e.g. incoming request is /products // The new URL is now /en-US/products
// The new URL is now /en-US/products return Response.redirect(request.nextUrl)
return NextResponse.redirect(
new URL(`/${locale}/${pathname}`, request.url)
)
}
} }
export const config = { export const config = {
......
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