Home > other >  Get path parameter on Next.js API
Get path parameter on Next.js API

Time:12-07

I have the following file

pages/api/[slug]/[uid].ts

And I want to get the slug and the uid on the body of my handler, how can I do it?

CodePudding user response:

You can make use of the useRouter() custom hook provided by the next for accessing query params in NextJs. It will return an object which will contain details of the url loaded, including the query params. The params will be stored within query key in the returned object. The query itself has an object as value, where key is the param name (here slug and uid) and its dynamic values as the values.

Then we can make use of the object destructuring for drilling into the required params.

  const router = useRouter();
  const { slug, uid } = router.query;

For accessing single param, we can do as follows,

  const router = useRouter();
  const slugValue = router.query.slug;
  const uidValue = router.query.uid;

CodePudding user response:

You can access it with req.query Just console.log it and see docs for more https://nextjs.org/docs/api-routes/dynamic-api-routes

  • Related