8

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})
3
  • With [postId][userId] there is no separator, the system won't know how to map a url to that route. Commented Aug 4, 2020 at 2:49
  • Maybe a [postId]/[userId] could do it, and you would have a folder named [userId] with index.js or just a file named [userId].js where you would fetch the data as you did Commented Aug 4, 2020 at 2:54
  • Does this answer your question? Dynamic routing with multiple parameters in Next js Commented Jan 23, 2023 at 17:59

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Your answer makes sense so I have to see why my second level [userId]gives me 404 but level 1 works. May be next js wants [...slug] or [...params] but I have to play with this
Works fine with the nested folder structure. Thanks
I think spreading [...slug] is intended for infinite parameters like in javascript, but with multiple segments in the case of Next JS. I don't really use API Routes, but I use file system routing a lot in Next. Try playing with them to see

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.