Topic 32 of 47
Fetching URL Parameters in Server Components
Overview
Beyond dynamic route segments (`params`), URLs often contain query strings (e.g., `?search=shoes&page=2`). In the App Router, Server Components access these via the `searchParams` prop.
Syntax
tsx
// URL: /search?query=laptop&sort=price
// app/search/page.tsx
export default function SearchPage({
searchParams,
}: {
searchParams: { [key: string]: string | string[] | undefined };
}) {
const query = searchParams.query; // "laptop"
const sort = searchParams.sort; // "price"
return (
<div>
<p>Searching for: {query}</p>
<p>Sort by: {sort}</p>
</div>
);
}Common Pitfalls
- The `searchParams` prop is only available on Page components (`page.tsx`), NOT on Layouts (`layout.tsx`). Layouts don't re-render on query changes.
- Accessing `searchParams` opts the page into Dynamic Rendering (Server-Side Rendering) because the values are not known at build time.
Real-World Example
Using search parameters for server-side pagination and filtering:
example
tsx
// app/products/page.tsx
// URL: /products?page=2&category=electronics
export default async function Products({ searchParams }) {
const page = parseInt(searchParams.page as string) || 1;
const category = searchParams.category as string || 'all';
// Fetch data directly using URL parameters
const products = await db.getProducts({ page, category });
return (
<ProductList products={products} currentPage={page} />
);
}