Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next js - How to pass multiple parameters in url for api?

I am able to pass one parameter and get results from next js api

The docs are very helpful - https://nextjs.org/docs/api-routes/dynamic-api-routes

/api/posts/[postId].js

The above works but is there an option to pass another parameter like below?

/api/posts/[postId][userId].js

The folder name is currently [postId]. I tried renaming it to [postId][userId]

My code for api is

  let postVotes = await req.db.collection('votesPosts').count({"post":req.query.postId,"user":req.query.userId})
like image 207
FKM Avatar asked Aug 04 '20 02:08

FKM


1 Answers

Usually, routes don't handle multiple parameters in a single segment of the URL path. You can only have one parameter per segment:

/api/entity/{param1}/{param2}/sub/{param3}

Now in Next JS, you need to separate them too to have 2 segments with param:

/api/posts/[postId]/[userId]

Which would resolve to 2 possible files:

/api/posts/postId]/[userId]/index.js

if you do it with a parameter directory + index file, or

/api/posts/postId]/[userId].js

if you do it with a parameter file.

Doing it with directory + index file allow you to add fixed segments like:

/api/posts/postId]/[userId]/popular.js
/api/posts/postId]/[userId]/private.js

Then you can make your API call as you did it for 2 params.

like image 53
KeitelDOG Avatar answered Sep 17 '22 12:09

KeitelDOG