Unverified Commit 0b74f518 authored by Vũ Văn Dũng's avatar Vũ Văn Dũng Committed by GitHub

docs: Add example on query parameters in route handlers (#55789)



### Why?

There is already an example of handling query parameters (`searchParams`) in route handler, but it's quite hidden (in [Opting out of caching](https://nextjs.org/docs/app/building-your-application/routing/route-handlers#opting-out-of-caching)). It made it hard for many developers to figure out how to do that: [there](https://discord.com/channels/752553802359505017/1127781032242974790) [are](https://discord.com/channels/752553802359505017/752647196419031042/1143181251856044042) [several](https://discord.com/channels/752553802359505017/752647196419031042/1146007247630106704) [people](https://discord.com/channels/752553802359505017/752647196419031042/1154623267164917861) who couldn't find that section in the documentation. (Linked are messages in the Next.js Discord server.)

Therefore this PR adds an example to the route handler documentation on how to do that, so developers can take reference more easily.
parent 8f7d83f1
...@@ -386,6 +386,28 @@ export async function GET(request, { params }) { ...@@ -386,6 +386,28 @@ export async function GET(request, { params }) {
| `app/items/[slug]/route.js` | `/items/b` | `{ slug: 'b' }` | | `app/items/[slug]/route.js` | `/items/b` | `{ slug: 'b' }` |
| `app/items/[slug]/route.js` | `/items/c` | `{ slug: 'c' }` | | `app/items/[slug]/route.js` | `/items/c` | `{ slug: 'c' }` |
### URL Query Parameters
The request object passed to the Route Handler is a `NextRequest` instance, which has [some additional convenience methods](/docs/app/api-reference/functions/next-request#nexturl), including for more easily handling query parameters.
```ts filename="app/api/search/route.ts" switcher
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
}
```
```js filename="app/api/search/route.js" switcher
export function GET(request) {
const searchParams = request.nextUrl.searchParams
const query = searchParams.get('query')
// query is "hello" for /api/search?query=hello
}
```
### Streaming ### Streaming
Streaming is commonly used in combination with Large Language Models (LLMs), such as OpenAI, for AI-generated content. Learn more about the [AI SDK](https://sdk.vercel.ai/docs). Streaming is commonly used in combination with Large Language Models (LLMs), such as OpenAI, for AI-generated content. Learn more about the [AI SDK](https://sdk.vercel.ai/docs).
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment