#Search Parameters
1 messages · Page 1 of 1 (latest)
Hi @stray basalt. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To get search parameters in a Next.js 14 server component or route handler, you have a couple of options depending on whether you're working with a page component or a route handler. Here's how you can access search parameters in each case:
- For Page Components (Server Components):
In a page component, you can access search parameters using the searchParams prop. This prop is automatically passed to the page component:
export default function Page({ searchParams }: { searchParams: { [key: string]: string | string[] | undefined } }) {
const query = searchParams.query
// Use the query parameter
}
Next.js Docs: Pages (https://nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional)
- For Route Handlers:
In a route handler (e.g., in app/api/search/route.ts), you can access search parameters using the NextRequest object:
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
}
Next.js Docs: Route Handlers (https://nextjs.org/docs/app/building-your-application/routing/route-handlers#url-query-parameters)
It's important to note that layouts do not receive the searchParams prop, as they are not re-rendered during navigation. If you need to access search parameters in a layout, you should use the useSearchParams hook in a Client Component instead.
Next.js Docs: Layouts (https://nextjs.org/docs/app/api-reference/functions/use-search-params#server-components)
Remember that when using search parameters, you should consider whether your page needs to be dynamically rendered or if it can be statically optimized. The behavior of search parameters can affect your rendering strategy.