Multi Nested Dynamic Routes in NextJs
Will Holmes
Posted on July 20, 2022
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
Posted on July 20, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 10, 2021