Next.jsEasy
How do you programmatically navigate in Next.js?
Use useRouter().push() or replace() in Client Components, redirect() or permanentRedirect() in Server Components, Server Functions and Route Handlers, and NextResponse.redirect() in proxy.ts.
Options by context
| Where | API |
|---|---|
| Client Component event handler | useRouter() from next/navigation |
| Server Component during render | redirect() from next/navigation |
| Server Function after a mutation | redirect() (after revalidating data) |
| Route Handler | redirect() or Response.redirect() |
| Before routing for many paths | NextResponse.redirect() in proxy.ts |
| Fixed, known redirects | redirects() in next.config.ts |
Details
redirect()throws a special error, so code after it does not run. Do not call it insidetry, or rethrow it.- In Server Functions, revalidate first (
updateTag,revalidatePath) and thenredirect, so the destination shows fresh data. permanentRedirect()sends a 308 status for content that moved for good.- In Client Components, wrap navigation in
startTransitionto track pending state. - In the browser you can also use
window.history.pushStateorreplaceState; Next.js syncs these withusePathnameanduseSearchParamswithout a server round-trip.
Pages Router
useRouter from next/router, Router.push outside components, and returning { redirect: { destination, permanent } } from getServerSideProps.
Code example
tsx
1// app/posts/actions.ts - Server Function2"use server";34import { redirect } from "next/navigation";5import { updateTag } from "next/cache";6import { db } from "@/lib/db";7import { verifySession } from "@/lib/auth";89export async function createPost(formData: FormData) {10 const user = await verifySession(); // always authorize inside the action11 const post = await db.post.create({12 data: { title: String(formData.get("title")), authorId: user.id },13 });1415 updateTag("posts"); // make the new post visible immediately16 redirect(`/posts/${post.id}`); // throws: nothing after this runs17}1819// app/admin/page.tsx - Server Component guard20// import { redirect } from "next/navigation";21// const user = await getUser();22// if (!user?.isAdmin) redirect("/login");2324// Client Component25// const router = useRouter();26// <button onClick={() => router.push("/checkout")}>Checkout</button>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.