Skip to content
Watch the complete Next.js 15 course on YouTube

Navigating programmatically

This page explains how to handle programmatic navigation in Next.js when Link components aren’t sufficient.

Next.js provides multiple ways to handle programmatic navigation when Link components aren’t sufficient. Common use cases include post-form submission redirects, authentication flows, and dynamic navigation based on user actions.

ZuseRouter hook

The useRouter hook from next/navigation enables programmatic navigation in client components. It provides methods for navigating between routes and managing browser history.

app/orders/confirm/page.tsx
"use client";
import { useRouter } from "next/navigation";
export default function OrderConfirmation() {
const router = useRouter();
const handleComplete = () => {
// Perform order completion logic
router.push("/orders/success");
};
return (
<div>
<h1>Complete Order</h1>
<button onClick={handleComplete}>Confirm Order</button>
</div>
);
}

The useRouter hook provides several navigation methods:

  • router.push(href) - Adds a new entry to the browser history
  • router.replace(href) - Replaces the current history entry
  • router.back() - Navigates to the previous page
  • router.forward() - Navigates to the next page
  • router.refresh() - Refreshes the current route

redirect function

For server-side navigation, use the redirect function from next/navigation. This is useful for scenarios like authentication checks or invalid parameters.

app/profile/page.tsx
import { redirect } from "next/navigation";
export default async function ProtectedPage() {
const user = await getUser();
if (!user) {
redirect("/login");
}
return <h1>Welcome {user.name}</h1>;
}

Common use cases

Programmatic navigation is particularly useful for:

  • Form submission redirects
  • Authentication flows
  • Dynamic navigation based on user actions
  • Error handling redirects

Good to know

  • useRouter requires the “use client” directive
  • redirect works in both server and client components
  • History management follows browser behavior