You can get query parameters in Server Components using the searchParams
prop.
Note that Next.js automatically injects the searchParams
prop into Server components’ props.
Let's say you have a URL like this: https://www.example.com/blog?category=react
You can access the category
query parameter, inside a component, say Blog, like this:
export default async function Blog({
searchParams,
}: {
searchParams: Promise<{ [key: string]: string | undefined }>
}) {
const category = (await searchParams).category
return (
<div>
<h1>Blog</h1>
{category && <p>Filtering by category: {category}</p>}
{/* Rest of your blog component */}
</div>
)
}
Note that searchParams
is a promise, so we use await
to resolve it into a plain JavaScript object containing the query parameters.
In this case, we extract the category
query parameter, which would be react
based on the example URL.