Routing, Navigation, and Dynamic SegmentsLesson 2.4
How to read search params and handle 404s in Next.js
searchParams prop, URLSearchParams, notFound function, not-found.tsx, redirect function, permanentRedirect
Reading Search Parameters
Server Components receive a searchParams prop containing the current URL's query string as a plain object. No need for useSearchParams or manual URL parsing.
// app/search/page.tsx
// URL: /search?q=nextjs&page=2
export default function SearchPage({
searchParams,
}: {
searchParams: { q?: string; page?: string }
}) {
const query = searchParams.q ?? ''
const page = Number(searchParams.page ?? 1)
return <p>Searching for: {query} (page {page})</p>
}Client Components must use the useSearchParams() hook from next/navigation instead.
Triggering a 404
import { notFound } from 'next/navigation'
export default async function ProductPage({ params }: { params: { id: string } }) {
const product = await getProduct(params.id)
if (!product) notFound() // Renders not-found.tsx
return <h1>{product.name}</h1>
}Redirects
import { redirect, permanentRedirect } from 'next/navigation'
// Temporary redirect (307)
redirect('/login')
// Permanent redirect (308) — for URL changes
permanentRedirect('/new-url')redirect() throws internally — it works like a thrown exception. Don't wrap it in try-catch. Call it at the top level of a Server Component or Server Action, not inside a nested async callback.
