Get path parameter on Next.js API

Viewed 1712

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?

2 Answers

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;
Related