redirect
The redirect
function allows you to redirect the user to another URL. redirect
can be used in Server Components, Client Components, Route Handlers, and Server Actions.
When used in a streaming context, this will insert a meta tag to emit the redirect on the client side. Otherwise, it will serve a 307 HTTP redirect response to the caller.
If a resource doesn't exist, you can use the notFound
function instead.
Good to know: If you prefer to return a 308 (Permanent) HTTP redirect instead of 307 (Temporary), you can use the
permanentRedirect
function instead.
Parameters
The redirect
function accepts two arguments:
redirect(path, type)
Parameter | Type | Description |
---|---|---|
path | string | The URL to redirect to. Can be a relative or absolute path. |
type | 'replace' (default) or 'push' (default in Server Actions) | The type of redirect to perform. |
By default, redirect
will use push
(adding a new entry to the browser history stack) in Server Actions and replace
(replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the type
parameter.
The type
parameter has no effect when used in Server Components.
Returns
redirect
does not return any value.
Example
Invoking the redirect()
function throws a NEXT_REDIRECT
error and terminates rendering of the route segment in which it was thrown.
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
does not require you to usereturn redirect()
as it uses the TypeScriptnever
type.
Version | Changes |
---|---|
v13.0.0 | redirect introduced. |
Was this helpful?