Recently i've been working on a web app that im building in NextJs along side a lot of other technologies (via create-t3-app). However, I came across a problem that I could not easily solve with some googling in the space of 15/20 minutes. So I thought that I would share my problem and solution, which will hopefully help others not go through the endless browsing of stackoverflow results as I did.
The Problem:
I want to have multiple nested dynamic routes in my NextJs app.
So that I can build routes like:
'/product-catalog/123/product/1'
Now before I carry on with my solution, i'd like to add that basic dynamic routing is so easy.
All you have to do is have a folder structure like so:
- pages/
-- product-catalog/
--- [productcatalogid].tsx
This would produce the route:
/product-catalog/123
(123 being the productcatalogid parameter)
However, moving to multiple nested routes isn't available using the same principle. I.e. a folder structure like so:
- pages/
-- product-catalog/
--- [productcatalogid].tsx
---- product/
----- [productid].tsx
The above will simply result in a 404 everytime you go to request the page.
The solution:
Simply implementing a folder structure like so:
- pages/
-- product-catalog/
--- index.tsx
---- product/
----- [productid].tsx
Seems to do the job nicely when dealing with multiple dynamic routes.
I hope this helped! For more information see the video that I found the solution on: https://www.youtube.com/watch?v=nfAxNTmme64
Top comments (5)
This was really helpful. Thanks!
There is something wrong within your code.
you forget to add square bracket to product-catalog folder
For a suggestion and another type of usage, you can use your folder structure like this;
What if "product-catalog/" has to be dynamic??
Mean:
if you watch the video, I think you add index.js in [product-catalog]/