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

548 views Asked by At

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.

2

There are 2 answers

2
alpha_N1618 On BEST ANSWER

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
}
1
oakX64 On

From the docs: https://nextjs.org/docs/pages/building-your-application/routing/api-routes#dynamic-api-routes

pages/api/post/[pid].ts

import type { NextApiRequest, NextApiResponse } from 'next'
     
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const { pid } = req.query
  res.end(`Post: ${pid}`)
}