Skip to content

Commit

Permalink
(docs): update i18n-routing.md (#33123)
Browse files Browse the repository at this point in the history
The recommended code for `_middleware.ts` does not work in prod, but does work locally.  You need to use `request.nextUrl.pathname` to properly redirect from what I can tell.  You also need to have a quick helper function to strip off the `/default` locale at the start of the pathname as we are providing `/en` as a fallback locale.

FWIW - I am pretty new to NextJS.  Someone with more experience should probably review this suggestion before merging it.  What I can tell you however is that the code as it is in `_middleware.ts` works locally but breaks in prod.  To test this out use the code and navigate to `https//www.mysite.com` - it will work as expected on the root url, as this matches `nextUrl.href`.  Now try navigating to `https//www.mysite.com/about` and you will be redirected to `https://www.mysite.com/en/https://www.mysite.com/about`.



## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`

Closes: #33762

Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
  • Loading branch information
ehowey and ijjk committed Feb 6, 2022
1 parent 7309098 commit 6890e3f
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion docs/advanced-features/i18n-routing.md
Expand Up @@ -170,14 +170,21 @@ import { NextRequest, NextResponse } from 'next/server'

const PUBLIC_FILE = /\.(.*)$/

const stripDefaultLocale = (str: string): string => {
const stripped = str.replace('/default', '')
return stripped
}

export function middleware(request: NextRequest) {
const shouldHandleLocale =
!PUBLIC_FILE.test(request.nextUrl.pathname) &&
!request.nextUrl.pathname.includes('/api/') &&
request.nextUrl.locale === 'default'

return shouldHandleLocale
? NextResponse.redirect(`/en${request.nextUrl.href}`)
? NextResponse.redirect(
`/en${stripDefaultLocale(request.nextUrl.pathname)}`
)
: undefined
}
```
Expand Down

0 comments on commit 6890e3f

Please sign in to comment.