Search code examples
apinext.jsurl-routing

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]


Solution

  • 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