Let's see how we can have access to search (or query) params in incoming request in NextJS 13 app
directory.
The scenario
We are making an internal fetch api call to http://localhost:3000/api/posts
. We are also trying to pass some query params like http://localhost:3000/api/posts?skip=2&take=4
for pagination. If we have posts [1, 2, 3, 4, 5, 6, 7, 8, 9]
, we want to skip [1, 2]
and take [3, 4, 5, 6]
only. The client code will look something like this:
const response = await fetch('http://localhost:3000/api/posts?skip=2&take=3')
In other frameworks, we could simply do something like
req.query
.
The problem
The problem was actually in the route handler part (solution is pretty easy). Here's the problem:
// app/api/posts/route.ts
import { NextRequest } from 'next/server';
export async function GET(req : NextRequest) {
// Property 'query' does not exist on type 'NextRequest'
const params = req.query
Here we could not access the skip
and take
part in our request url.
The solution
We just have to convert the req.url
which is a string, into a url object using new URL()
with req.url
as the input. Then we can easily access any part of url params like this:
export async function GET(req : NextRequest) {
const url = new URL(req.url)
const skip = url.searchParams.get("skip")
const take = url.searchParams.get("take")
And there we have our search params. The typescript type is string | undefined
.
Oldest comments (3)
Thanks a lot man for making post on this problem. really helpful.
I am looking for /api/books/3 and I've actually found it by trying:
Hopefully these keywords work for google search:
route parameter nextJS 13 app directory route handler
Thanks a lot Man