Skip to content

Commit

Permalink
docs: Add example on query parameters in route handlers (#55789)
Browse files Browse the repository at this point in the history
### 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.
  • Loading branch information
joulev authored Sep 24, 2023
1 parent 8f7d83f commit 0b74f51
Showing 1 changed file with 22 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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/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 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).
Expand Down

0 comments on commit 0b74f51

Please sign in to comment.