Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct folder structure for dynamic nested routes in Next.js?

I've been going over the Next.js docs and think I understand the [slug].js dynamic routing process, but I struggling to understand nested dynamic routes in terms of folder structure.

If I want to make a user based application, how would I achieve /user/[userid]/post/[postId]?

And a would like something like this:

 user
 - [id].js // e.g. user/1
 - [userId]
 - - post
 - - - [postId].js // e.g. user/[userId]/post/[postId]

But this throws an error about [slugs] as I think you can't have two slugs in the same folder.

Can anyone explain the correct folder structure to achieve this? Any help with be greatly appreciated.

like image 739
Thomas Allen Avatar asked Feb 02 '26 05:02

Thomas Allen


1 Answers

Instead of [id].js create an file named index.js in [userId] folder which will be used to render the page for route path /user/[userId]/.

pages/
 user/
  [userId]/
    - index.js        // will match for /user/1234
    post/
      - index.js      // will match for /user/1234/post
      - [postId].js   // will match for /user/1234/post/some-post

Similarly creating an index.js under folder post will be useful to match for route path /user/[userId]/post/ which can be used show a list for post for that user.

An example with a folder structure for a similar use case.

like image 117
subashMahapatra Avatar answered Feb 04 '26 19:02

subashMahapatra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!