#How to get query params other context in

1 messages · Page 1 of 1 (latest)

kindred dagger
north jungleBOT
#

Hi @kindred dagger. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

kindred dagger
#

@north jungle How to get query params & other context in route handlers? Given the following example:

import { NextResponse } from 'next/server';
export async function GET(request: Request, context: { params }) {
    const team = params.team; // '1'
    return NextResponse.json({ data })
  }
north jungleBOT
#

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

#

Sorry @kindred dagger, I seem to be having a bit of trouble. Don't worry though, I've pinged my supprt and they will try to fix me up! :technologist:

Perhaps try again in 15mins?

#

To get query parameters and other context in route handlers, you can use the request object, which is a NextRequest (https://beta.nextjs.org/docs/api-reference/request) object. This object extends the Web Request (https://developer.mozilla.org/en-US/docs/Web/API/Request) API and provides additional control over the incoming request, including easily accessing cookies and an extended, parsed URL object nextUrl.

For example, to get query parameters, you can use the nextUrl object:

import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest, context: { params }) {
  const { nextUrl } = request;
  const queryParams = nextUrl.searchParams;

  const team = context.params.team; // '1'

  // Access query parameters using queryParams.get('paramName')
  const exampleQueryParam = queryParams.get('example');

  return NextResponse.json({ data: { team, exampleQueryParam } });
}

In this example, the nextUrl object is used to access the query parameters. You can then use the searchParams property and the get method to retrieve the values of specific query parameters.

Remember that the context object contains the params property, which holds the dynamic route parameters (https://beta.nextjs.org/docs/routing/defining-routes#dynamic-segments) for the current route. In your example, you're already accessing the team parameter using context.params.team.

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

NextRequest extends the Web Request API with additional methods and properties.

The Request interface of the Fetch API represents a resource request.

Learn how to create routes in your Next.js application.