#access search params on server
1 messages · Page 1 of 1 (latest)
Hi @mortal oxide. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, you can access search parameters on the server in a few different ways depending on the context:
-
In Pages (Server Components): You can use the
searchParamsprop. This is available in the props of your page component. Here is the documentation (https://nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional) for more details. -
In Route Handlers: The request object passed to the Route Handler is a
NextRequestinstance, which has some additional convenience methods, including for more easily handling query parameters. Here is an example:
import { type NextRequest } from 'next/server'
export function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams
const query = searchParams.get('query')
// query is "hello" for /api/search?query=hello
}
You can find more details in the documentation (https://nextjs.org/docs/app/building-your-application/routing/router-handlers).
- In Client Components: You can use the
useSearchParamshook from 'next/navigation'. This hook will be available on the server during the initial server render of the Client Component if the route is dynamically rendered. Here is an example:
'use client'
import { useSearchParams } from 'next/navigation'
export default function SearchBar() {
const searchParams = useSearchParams()
const search = searchParams.get('search')
// This will be logged on the server during the initial render
// and on the client on subsequent navigations.
console.log(search)
return <>Search: {search}</>
}
Here is the documentation (https://nextjs.org/docs/app/api-reference/functions/use-search-params) for more details.