redirect
Theredirect function allows you to redirect the user to another URL.redirect can be used while rendering inServer and Client Components,Route Handlers, andServer Actions.
When used in astreaming context, this will insert a meta tag to emit the redirect on the client side. When used in a server action, it will serve a 303 HTTP redirect response to the caller. Otherwise, it will serve a 307 HTTP redirect response to the caller.
If a resource doesn't exist, you can use thenotFound function instead.
Reference
Parameters
Theredirect 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 usepush (adding a new entry to the browser history stack) inServer Actions andreplace (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying thetype parameter.
TheRedirectType object contains the available options for thetype parameter.
import { redirect, RedirectType }from'next/navigation'redirect('/redirect-to',RedirectType.replace)// orredirect('/redirect-to',RedirectType.push)Thetype parameter has no effect when used in Server Components.
Returns
redirect does not return a value.
Behavior
- In Server Actions and Route Handlers, redirect should be calledoutside the
tryblock when usingtry/catchstatements. - If you prefer to return a 308 (Permanent) HTTP redirect instead of 307 (Temporary), you can use the
permanentRedirectfunction instead. redirectthrows an error so it should be calledoutside thetryblock when usingtry/catchstatements.redirectcan be called in Client Components during the rendering process but not in event handlers. You can use theuseRouterhook instead.redirectalso 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.jsorProxy.
Example
Server Component
Invoking theredirect() function throws aNEXT_REDIRECT error and terminates rendering of the route segment in which it was thrown.
import { redirect }from'next/navigation'asyncfunctionfetchTeam(id:string) {constres=awaitfetch('https://...')if (!res.ok)returnundefinedreturnres.json()}exportdefaultasyncfunctionProfile({ params,}: { params:Promise<{ id:string }>}) {const {id }=await paramsconstteam=awaitfetchTeam(id)if (!team) {redirect('/login') }// ...}Good to know:
redirectdoes not require you to usereturn redirect()as it uses the TypeScriptnevertype.
Client Component
redirect can be directly used in a Client Component.
'use client'import { redirect, usePathname }from'next/navigation'exportfunctionClientRedirect() {constpathname=usePathname()if (pathname.startsWith('/admin')&&!pathname.includes('/login')) {redirect('/admin/login') }return <div>Login Page</div>}Good to know: When using
redirectin a Client Component on initial page load during Server-Side Rendering (SSR), it will perform a server-side redirect.
redirect can be used in a Client Component through a Server Action. If you need to use an event handler to redirect the user, you can use theuseRouter hook.
'use client'import { navigate }from'./actions'exportfunctionClientRedirect() {return ( <formaction={navigate}> <inputtype="text"name="id" /> <button>Submit</button> </form> )}'use server'import { redirect }from'next/navigation'exportasyncfunctionnavigate(data:FormData) {redirect(`/posts/${data.get('id')}`)}FAQ
Why doesredirect use 307 and 308?
When usingredirect() you may notice that the status codes used are307 for a temporary redirect, and308 for a permanent redirect. While traditionally a302 was used for a temporary redirect, and a301 for a permanent redirect, many browsers changed the request method of the redirect, from aPOST toGET request when using a302, regardless of the origins request method.
Taking the following example of a redirect from/users to/people, if you make aPOST request to/users to create a new user, and are conforming to a302 temporary redirect, the request method will be changed from aPOST to aGET request. This doesn't make sense, as to create a new user, you should be making aPOST request to/people, and not aGET request.
The introduction of the307 status code means that the request method is preserved asPOST.
302- Temporary redirect, will change the request method fromPOSTtoGET307- Temporary redirect, will preserve the request method asPOST
Theredirect() method uses a307 by default, instead of a302 temporary redirect, meaning your requests willalways be preserved asPOST requests.
Learn more about HTTP Redirects.
Version History
| Version | Changes |
|---|---|
v13.0.0 | redirect introduced. |
Was this helpful?