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.
"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 historyrouter.replace(href)
- Replaces the current history entryrouter.back()
- Navigates to the previous pagerouter.forward()
- Navigates to the next pagerouter.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.
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” directiveredirect
works in both server and client components- History management follows browser behavior