Redirects, Get Current Route & Linking
In Server Components, Server Actions, and Route Handlers, call redirect("/login") from next/navigation to send the user elsewhere (307 temporary by default in many cases).
redirect() and permanentRedirect()
In Server Components, Server Actions, and Route Handlers, call redirect("/login") from next/navigation to send the user elsewhere (307 temporary by default in many cases).
permanentRedirect("/new-path") signals a permanent move (308) — good when a URL has moved forever (SEO-friendly).
Real-life example: redirect is a temporary "floor closed, use stairs" sign. permanentRedirect is changing the building address on Google Maps for good.
import { redirect, permanentRedirect } from "next/navigation";
export default async function BillingPage() {
const session = await getSession(); // your auth helper
if (!session) {
redirect("/login"); // temporary — come back after login
}
if (session.plan === "legacy") {
permanentRedirect("/billing/v2"); // old URL retired
}
return <h1>Billing for {session.email}</h1>;
}usePathname, useParams, useSearchParams
In Client Components, read the current route with hooks from next/navigation. usePathname() returns the path string. useParams() returns dynamic segments. useSearchParams() reads ?query= values.
Wrap components that use useSearchParams in a <Suspense> boundary when Next.js asks — it can opt the page into client rendering of that part.
Real-life example: These hooks are looking at your phone's GPS and address bar — where you are, which room number, and what filters you typed.
"use client";
import Link from "next/link";
import {
usePathname,
useParams,
useSearchParams,
} from "next/navigation";
export default function CourseToolbar() {
const pathname = usePathname();
const params = useParams<{ id: string }>();
const searchParams = useSearchParams();
const tab = searchParams.get("tab") ?? "overview";
return (
<div>
<p>Path: {pathname}</p>
<p>Course id: {params.id}</p>
<p>Tab: {tab}</p>
<Link
href={`/courses/${params.id}?tab=lessons`}
style={{ fontWeight: tab === "lessons" ? "bold" : "normal" }}
>
Lessons
</Link>
</div>
);
}Redirects in next.config
For static URL moves (old marketing links, renamed paths), configure redirects in next.config — they run before React renders.
Use this for SEO migrations and short links. Use redirect() in code when the decision depends on session, role, or database state.
Real-life example: next.config redirects are printed street signs at the city edge. Code redirects are a receptionist checking your ID before sending you upstairs.
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
async redirects() {
return [
{
source: "/old-blog/:slug",
destination: "/blog/:slug",
permanent: true,
},
{
source: "/go/nextjs",
destination: "/courses/nextjs",
permanent: false,
},
];
},
};
export default nextConfig;