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

WhereAPI
Client Component event handleruseRouter() from next/navigation
Server Component during renderredirect() from next/navigation
Server Function after a mutationredirect() (after revalidating data)
Route Handlerredirect() or Response.redirect()
Before routing for many pathsNextResponse.redirect() in proxy.ts
Fixed, known redirectsredirects() in next.config.ts

Details

  • redirect() throws a special error, so code after it does not run. Do not call it inside try, or rethrow it.
  • In Server Functions, revalidate first (updateTag, revalidatePath) and then redirect, so the destination shows fresh data.
  • permanentRedirect() sends a 308 status for content that moved for good.
  • In Client Components, wrap navigation in startTransition to track pending state.
  • In the browser you can also use window.history.pushState or replaceState; Next.js syncs these with usePathname and useSearchParams without 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 Function
2"use server";
3
4import { redirect } from "next/navigation";
5import { updateTag } from "next/cache";
6import { db } from "@/lib/db";
7import { verifySession } from "@/lib/auth";
8
9export async function createPost(formData: FormData) {
10 const user = await verifySession(); // always authorize inside the action
11 const post = await db.post.create({
12 data: { title: String(formData.get("title")), authorId: user.id },
13 });
14
15 updateTag("posts"); // make the new post visible immediately
16 redirect(`/posts/${post.id}`); // throws: nothing after this runs
17}
18
19// app/admin/page.tsx - Server Component guard
20// import { redirect } from "next/navigation";
21// const user = await getUser();
22// if (!user?.isAdmin) redirect("/login");
23
24// Client Component
25// 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.

Open in study app