Unverified Commit e6e95f42 authored by Sam Ko's avatar Sam Ko Committed by GitHub

chore: update docs around redirect() (#61334)

## Description
- Add a sentence for clarifying redirecting in a Server Component
- Fixes https://github.com/vercel/next.js/issues/61315

Closes NEXT-2284

---------
Co-authored-by: 's avatarZack Tanner <zacktanner@gmail.com>
parent e4b35313
...@@ -7,10 +7,11 @@ related: ...@@ -7,10 +7,11 @@ related:
- app/building-your-application/configuring/typescript - app/building-your-application/configuring/typescript
--- ---
There are three ways to navigate between routes in Next.js: There are four ways to navigate between routes in Next.js:
- Using the [`<Link>` Component](#link-component) - Using the [`<Link>` Component](#link-component)
- Using the [`useRouter` Hook](#userouter-hook) - Using the [`useRouter` hook](#userouter-hook) ([Client Components](/docs/app/building-your-application/rendering/client-components))
- Using the [`redirect` function](#redirect-function) ([Server Components](/docs/app/building-your-application/rendering/server-components))
- Using the native [History API](#using-the-native-history-api) - Using the native [History API](#using-the-native-history-api)
This page will go through how to use each of these options, and dive deeper into how navigation works. This page will go through how to use each of these options, and dive deeper into how navigation works.
...@@ -160,9 +161,9 @@ const router = useRouter() ...@@ -160,9 +161,9 @@ const router = useRouter()
router.push('/dashboard', { scroll: false }) router.push('/dashboard', { scroll: false })
``` ```
## `useRouter()` Hook ## `useRouter()` hook
The `useRouter` hook allows you to programmatically change routes from Client Components. For Server Components, you would [`redirect()`](/docs/app/api-reference/functions/redirect) instead. The `useRouter` hook allows you to programmatically change routes from [Client Components](/docs/app/building-your-application/rendering/client-components).
```jsx filename="app/page.js" ```jsx filename="app/page.js"
'use client' 'use client'
...@@ -184,6 +185,58 @@ For a full list of `useRouter` methods, see the [API reference](/docs/app/api-re ...@@ -184,6 +185,58 @@ For a full list of `useRouter` methods, see the [API reference](/docs/app/api-re
> **Recommendation:** Use the `<Link>` component to navigate between routes unless you have a specific requirement for using `useRouter`. > **Recommendation:** Use the `<Link>` component to navigate between routes unless you have a specific requirement for using `useRouter`.
## `redirect` function
For [Server Components](/docs/app/building-your-application/rendering/server-components), use the `redirect` function instead.
```tsx filename="app/team/[id]/page.tsx" switcher
import { redirect } from 'next/navigation'
async function fetchTeam(id: string) {
const res = await fetch('https://...')
if (!res.ok) return undefined
return res.json()
}
export default async function Profile({ params }: : { params: { id: string }) {
const team = await fetchTeam(params.id)
if (!team) {
redirect('/login')
}
// ...
}
```
```jsx filename="app/team/[id]/page.js" switcher
import { redirect } from 'next/navigation'
async function fetchTeam(id) {
const res = await fetch('https://...')
if (!res.ok) return undefined
return res.json()
}
export default async function Profile({ params }) {
const team = await fetchTeam(params.id)
if (!team) {
redirect('/login')
}
// ...
}
```
> **Good to know**:
>
> - `redirect` returns a 307 (Temporary Redirect) status code by default. When used in a Server Action, it returns a 303 (See Other), which is commonly used for redirecting to a success page as a result of a POST request.
> - `redirect` internally throws an error so it should be called outside of `try/catch` blocks.
> - `redirect` can be called in Client Components during the rendering process but not in event handlers. You can use the [`useRouter` hook](#userouter-hook) instead.
> - `redirect` also accepts absolute URLs and can be used to redirect to external links.
> - If you'd like to redirect before the render process, use [`next.config.js`](/docs/app/building-your-application/routing/redirecting#redirects-in-nextconfigjs) or [Middleware](/docs/app/building-your-application/routing/redirecting#nextresponseredirect-in-middleware).
See the [`redirect` API reference](/docs/app/api-reference/functions/redirect) for more information.
## Using the native History API ## Using the native History API
Next.js allows you to use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page. Next.js allows you to use the native [`window.history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`window.history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods to update the browser's history stack without reloading the page.
...@@ -298,7 +351,7 @@ The App Router uses a hybrid approach for routing and navigation. On the server, ...@@ -298,7 +351,7 @@ The App Router uses a hybrid approach for routing and navigation. On the server,
Code splitting allows you to split your application code into smaller bundles to be downloaded and executed by the browser. This reduces the amount of data transferred and execution time for each request, leading to improved performance. Code splitting allows you to split your application code into smaller bundles to be downloaded and executed by the browser. This reduces the amount of data transferred and execution time for each request, leading to improved performance.
Server Components allow your application code to be automatically code-split by route segments. This means only the code needed for the current route is loaded on navigation. [Server Components](/docs/app/building-your-application/rendering/server-components) allow your application code to be automatically code-split by route segments. This means only the code needed for the current route is loaded on navigation.
### 2. Prefetching ### 2. Prefetching
......
...@@ -80,7 +80,7 @@ export async function createPost(id) { ...@@ -80,7 +80,7 @@ export async function createPost(id) {
> **Good to know**: > **Good to know**:
> >
> - `redirect` returns a 307 (Temporary Redirect) status code by default. When used in a Server Action, it returns a 303 (See Other), which is commonly used for redirecting to a success page as a result of a POST request. > - `redirect` returns a 307 (Temporary Redirect) status code by default. When used in a Server Action, it returns a 303 (See Other), which is commonly used for redirecting to a success page as a result of a POST request.
> - `redirect` internally throws an error so should be called outside of `try/catch` blocks. > - `redirect` internally throws an error so it should be called outside of `try/catch` blocks.
> - `redirect` can be called in Client Components during the rendering process but not in event handlers. You can use the [`useRouter` hook](#userouter-hook) instead. > - `redirect` can be called in Client Components during the rendering process but not in event handlers. You can use the [`useRouter` hook](#userouter-hook) instead.
> - `redirect` also accepts absolute URLs and can be used to redirect to external links. > - `redirect` also accepts absolute URLs and can be used to redirect to external links.
> - If you'd like to redirect before the render process, use [`next.config.js`](#redirects-in-nextconfigjs) or [Middleware](#nextresponseredirect-in-middleware). > - If you'd like to redirect before the render process, use [`next.config.js`](#redirects-in-nextconfigjs) or [Middleware](#nextresponseredirect-in-middleware).
...@@ -139,7 +139,7 @@ See the [`permanentRedirect` API reference](/docs/app/api-reference/functions/pe ...@@ -139,7 +139,7 @@ See the [`permanentRedirect` API reference](/docs/app/api-reference/functions/pe
</AppOnly> </AppOnly>
## `useRouter` hook ## `useRouter()` hook
<AppOnly> <AppOnly>
...@@ -216,7 +216,6 @@ export default function Page() { ...@@ -216,7 +216,6 @@ export default function Page() {
> **Good to know**: > **Good to know**:
> >
> - If you don't need to programatically navigate a user, you should use a [`<Link>`](/docs/app/api-reference/components/link) component. > - If you don't need to programatically navigate a user, you should use a [`<Link>`](/docs/app/api-reference/components/link) component.
> - `redirect` in the App Router also accepts absolute URLs and can be used to redirect to external links. For the Pages Router, you can use [window.location](https://developer.mozilla.org/en-US/docs/Web/API/Window/location).
<AppOnly> <AppOnly>
......
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