Careeroza
redirect and notFound
Server-side Redirect
In Server Components, Route Handlers and Server Actions, call redirect() from next/navigation. It stops rendering and sends the user elsewhere (it works by throwing a special error, so do not wrap it in try/catch).
app/account/page.tsx
import { redirect } from 'next/navigation';
import { getCurrentUser } from '@/lib/auth';
export default async function AccountPage() {
const user = await getCurrentUser();
if (!user) redirect('/login?next=/account');
return <h1>Hello, {user.name}</h1>;
}Example
curl -i http://localhost:3000/accountExample output
HTTP/1.1 307 Temporary Redirect location: /login?next=/account
notFound()
notFound() renders the nearest not-found.tsx and returns HTTP 404. Use it when a product id does not exist.
import { notFound } from 'next/navigation';
import { getProduct } from '@/lib/products';
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const product = await getProduct(Number(id));
if (!product) notFound();
return <h1>{product.name}</h1>;
}Example
curl -i http://localhost:3000/products/99999Example output
HTTP/1.1 404 Not Found content-type: text/html; charset=utf-8
Which One to Use
| Need | Use |
|---|---|
| Navigate after a click (browser) | <Link> or router.push |
| Send the user away during server rendering | redirect() (307) or permanentRedirect() (308) |
| Old URL moved forever | redirects() in next.config.ts |
| Resource does not exist | notFound() |