DEV Community

Cover image for How to access URL params in incoming request (Nextjs 13.4 Route handlers)
Bikrant
Bikrant

Posted on • Updated on

How to access URL params in incoming request (Nextjs 13.4 Route handlers)

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')
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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")


Enter fullscreen mode Exit fullscreen mode

And there we have our search params. The typescript type is string | undefined.

Oldest comments (3)

Collapse
 
awaisalwaisy profile image
Alwaisy al-waisy

Thanks a lot man for making post on this problem. really helpful.

Collapse
 
dejoma profile image
Dennis • Edited

I am looking for /api/books/3 and I've actually found it by trying:

export async function GET(req: Request, route: { params: { id: string } }) {
  const id: number = Number(route.params.id);
  return new Response(JSON.stringify({ id }), { status: 200 });
}
Enter fullscreen mode Exit fullscreen mode

Hopefully these keywords work for google search:
route parameter nextJS 13 app directory route handler

Collapse
 
nayemhossain profile image
Md Nayem Hossain

Thanks a lot Man