Hannan Rhodes
Hannan Rhodes

Reputation: 89

How to create an static api route after a dynamic route in Next.js?

I have an api that dynamically pulls a post. localhost/api/post/[postId]

I want to extend functionality to retrieve the comments of the post at the URL localhost/api/post/[postId]/comments

What is the correct way to structure this in Next.js? I am thinking to create a dynamic route and check if the query equals comment? localhost/api/post/[postId]/[comment]

Upvotes: 0

Views: 278

Answers (1)

Alvaro Luque
Alvaro Luque

Reputation: 26

The following file structure should work:

/pages/api/post/[postId]/index.js       //Route: /api/post/1
/pages/api/post/[postId]/comments.js    //Route: /api/post/1/comments

Besides that, just to follow good practices, I would recommend that you rename "post" to "posts", like that:

/pages/api/posts/[postId]/comments.js

Upvotes: 1

Related Questions