redirect()
Redirects the user to another URL from Server Components, actions, or handlers.
Syntax
import { redirect } from 'next/navigation'; redirect(path, type?) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
path | string | Yes | Absolute or relative URL to redirect to. |
type | 'replace' | 'push' | No | History behavior in Server Actions (default `replace`). |
Returns
never — Throws an internal error to halt rendering and redirect.
Examples
import { redirect } from 'next/navigation'
export default async function Page() {
const user = await getUser()
if (!user) redirect('/login')
return <Dashboard user={user} />
}
'use server'
import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) {
const post = await db.posts.create({ title: formData.get('title') })
redirect(`/posts/${post.id}`)
}
Notes
Issues a 307 (Server Action) or 303 redirect. It throws a special
error, so do NOT wrap it in try/catch and do not call it after a
`try` that catches everything; place it outside try/catch or rethrow.
Returns `never`, so no code after it runs. Use `permanentRedirect`
for 308. Status code 307/303 by default.