Next.js Sub-Pages for parameterized routes

Viewed 51

Right now, my routing looks like this:

https://app.com/users opens pages/users/index.js
https://app.com/users/:userid opens pages/users/[id].js

I want to create route, for example:

https://app.com/users/:id/friends -> show all friends for the user or even
https://app.com/users/:id/friends/:friendId -> show a specific friend

I have tried

pages
    users
        index.js
        [id].js
        friends
            index.js
            [friendId].js

but i can only reach users/friends and not `users/:id/friends``

How do i set my pages directory so i can use this sort of routing?

Also, I want to be able to access id and friendId in the context of getServerSideProps...

2 Answers

If you don't get the answer description well, pls follow the diagram I made.

If you want this https://app.com/users/:id/friends, then you should create something like this:

pages/users/index.js/[id]/index.js/friends.js

So to make this clear, you have a folder name pages (where all pages folder and files are), then you have a user folder (this takes an index.js which means user path). Now in the user folder, you have to create a folder named [id], in this folder you should create a file name index.js, this index.js stand for the :id. The last thing is to create the friend.js in the [id] folder.

Something like this.

pages ----------------- Main folder
    users ------------- A folder inside `pages` folder  
       index.js ------- A file inside `users` folder == `https://app.com/users`
       [id] ----------- A folder inside `users` folder
          index.js ---- A file inside `[id]` folder ==`https://app.com/users/:id`
          friends.js -- A file inside `[id]` folder == `https://app.com/users/:id/friends`

If you want something like this https://app.com/users/:id/friends/:friendId

Then you will have to do something like this:

pages ------------------------- Main folder
    users --------------------- A folder inside `pages` folder  
       index.js --------------- A file inside `users` folder == `https://app.com/users`
       [id] ------------------- A folder inside `users` folder
          index.js ------------ A file inside `[id]` folder ==`https://app.com/users/:id`
             [friends] -------- A folder inside `[id]` folder
                index.js ------ A file inside `[friends]` folder
                friendId.js --- A file inside `[friends]` folder

You can use Dynamic Routing syntax in your folders instead of a file in order to nest them (create a folder [id] instead of a file [id].js). For your specific example it would look like this:

pages
    users
       index.js
       [id]
          friends
               [friendId].js
Related