#test

1 messages · Page 1 of 1 (latest)

fierce knoll
#

how to get query params in nextjs 14 app directory

echo galeBOT
#

Hi @fierce knoll. 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 14, when using the app directory structure, you can access query parameters from the request object passed to the Route Handler. This request object is an instance of NextRequest, which has some additional convenience methods for handling query parameters.

Here's an example of how you can do this:

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
}

In this example, searchParams is a URLSearchParams object representing the query parameters of the URL. You can use the get method on this object to retrieve the value of a specific query parameter.

For more information, you can refer to the Next.js documentation (https://nextjs.org/docs/app/building-your-application/routing/route-handlers#url-query-parameters).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@fierce knoll kapa.ai is still learning and improving, please let us know how it did by reacting below

fierce knoll
#

i mean in react server component (page) not api
@echo gale

echo galeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In Next.js, to access the URL or query parameters on a server-side page component, you can use the params and searchParams props respectively.

Here's how you can access the route segments:

function Page({ params }) {
  // params is an object containing the route segments
  // For example, for the route /app/{param1}/abc/{param2}, params would be { param1: 'value1', param2: 'value2' }
}

And here's how you can access the URL search parameters:

function Page({ searchParams }) {
  // searchParams is a URLSearchParams object representing the query parameters of the URL
  // You can use the get method on this object to retrieve the value of a specific query parameter
  const query = searchParams.get('query');
}

Please note that these props are available by default for server components. If you are using client components, you can use hooks like usePathname, useSelectedLayoutSegment, and useSelectedLayoutSegments for more complex routes.

For more information, you can refer to the Next.js documentation (https://nextjs.org/docs/app#how-can-i-access-the-url-on-a-page).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: