Unverified Commit 2e3e56d9 authored by Max Leiter's avatar Max Leiter Committed by GitHub

docs/next/link: Mention middleware + dynamic routes changes (#42607)

Documents the next 13 changes requiring `as` and `href` using `next/link` with Dynamic Routes.

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm build && pnpm lint`
Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent 2358e9c2
......@@ -218,3 +218,43 @@ The default behavior of `Link` is to scroll to the top of the page. When there i
Disables scrolling to the top
</Link>
```
## With Next.js 13 Middleware
It's common to use [Middleware](/docs/advanced-features/middleware) for authentication or other purposes that involve rewriting the user to a different page. In order for the `<Link />` component to properly prefetch links with rewrites via Middleware, you need to tell Next.js both the URL to display and the URL to prefetch. This is required to avoid un-necessary fetches to middleware to know the correct route to prefetch.
For example, if you have want to serve a `/dashboard` route that has authenticated and visitor views, you may add something similar to the following in your Middleware to redirect the user to the correct page:
```js
// middleware.js
export function middleware(req) {
const nextUrl = req.nextUrl
if (nextUrl.pathname === '/dashboard') {
if (req.cookies.authToken) {
return NextResponse.rewrite('/auth/dashboard')
} else {
return NextResponse.rewrite('/public/dashboard')
}
}
}
```
In this case, you would want to use the following code in your `<Link />` component (inside `pages/`):
```js
// pages/index.js
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed'
export default function Page() {
const isAuthed = useIsAuthed()
const path = isAuthed ? '/auth/dashboard' : '/dashboard'
return (
<Link as="/dashboard" href={path}>
Dashboard
</Link>
)
}
```
> **Note:** If you're using [Dynamic Routes](/docs/routing/dynamic-routes), you'll need to adapt your `as` and `href` props. For example, if you have a Dynamic Route like `/dashboard/[user]` that you want to present differently via middleware, you would write: `<Link href={{ pathname: '/dashboard/authed/[user]', query: { user: username } }} as="/dashboard/[user]">Profile</Link>`.
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