Search code examples
next.js13next-routernext-api

Using Next 13.5.6 & App Router, how to get params of dynamic route?


I am building a sample REST API with Next 13 just for practicing, did It with node and express, worked well. Now I am trying to do It with Next and App Router. I have a folder api inside app, where I have a folder products, and inside a folder named [id] with Its GET method. When I go to /api/procuts/15, for example, It works and goes to the GET route, but I am not being able to get that "15" without cutting It from the URL. Isn't there a way to get it like in node with req.params? (BTW using TypeScript)

I tried with NextRequest reading all info It comes with It and there is no query. I am obtaining the ID through "const id = req.url.split("products/")[1]" and works, but I am trying to look for a way to receive It similar to Node or with pages router with NextApiRequest.query. Tried with useNavigate, useSearchParams, useRouter (I know some are for pages Router, but had to give It a try) and all of them are for client pages, not server.


Solution

  • You can use below code to get your id
    if your route is /api/products/[id]

    const Page = async ({ params }: { params: { id: string } }) => {
      console.log(params?.id); // this should give your dynamic route id
    }