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
.
Top comments (5)
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 for making post on this problem. really helpful.
Thanks! That worked. The Next.js community have given themselves a great advantage by abusing any and all humane programming conventions and standards.
A change so breaking should not be allowed or acceptable.
If previously our routers were written in a certain way, any and all future changes must be made to accommodate the original design of the application:
1.) To prevent breaking
2.) To respect established conventions of the framework.
These people think it is okay to make up the rules as you go, but as you can see this is not true and we do not stand of it.
Thanks for your post. I hope more people from Vercel see this and do tremendously better in the future.
Also, this works
Thanks a lot Man