Next.js Routing
Dynamic segments, catch-all routes, navigation, and route groups
Overview
Next.js maps folders in app/ to URL paths. Dynamic segments ([id]), catch-all ([...slug]), and optional catch-all ([[...slug]]) handle variable routes. Use Link and useRouter for navigation.
Syntax / Usage
app/
shop/
page.tsx # /shop
[category]/
page.tsx # /shop/electronics
[productId]/page.tsx # /shop/electronics/42
docs/
[...slug]/page.tsx # /docs/a/b/c
import Link from 'next/link'
import { redirect, notFound } from 'next/navigation'
// Dynamic page
export default async function Page({
params,
}: {
params: Promise<{ category: string; productId: string }>
}) {
const { productId } = await params
const product = await getProduct(productId)
if (!product) notFound()
return <ProductView product={product} />
}
// Programmatic navigation (Client)
'use client'
import { useRouter } from 'next/navigation'
function GoHome() {
const router = useRouter()
return <button onClick={() => router.push('/')}>Home</button>
}
Examples
Active link styling:
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
function NavLink({ href, children }) {
const pathname = usePathname()
const active = pathname === href
return (
<Link href={href} className={active ? 'font-bold' : ''}>
{children}
</Link>
)
}
Redirect after login:
async function loginAction(formData: FormData) {
'use server'
if (await authenticate(formData)) redirect('/dashboard')
}
Common Mistakes
- Using
next/routerfrom Pages Router instead ofnext/navigationin App Router - Hardcoding URLs instead of centralized route helpers
- Forgetting
notFound()for missing dynamic resources - Route groups
(name)confused with URL segments
See Also
app-router middleware metadata server-components