DEV Community

Will Holmes
Will Holmes

Posted on

Multi Nested Dynamic Routes in NextJs

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
Enter fullscreen mode Exit fullscreen mode

This would produce the route:

/product-catalog/123
(123 being the productcatalogid parameter)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
devwax profile image
Steve Monsen

This was really helpful. Thanks!

Collapse
 
azariaberyl profile image
Azaria Beryl

There is something wrong within your code.

- pages/
-- [product-catalog]/
--- index.tsx
--- product/
---- [productid].tsx
Enter fullscreen mode Exit fullscreen mode

you forget to add square bracket to product-catalog folder

Collapse
 
menesyurtlu profile image
Enes Yurtlu • Edited

For a suggestion and another type of usage, you can use your folder structure like this;

  1. - pages
  2. --product-catalog
  3. --- index.tsx
  4. ---- product
  5. ----- index.tsx and you can nest how many times you want.
Collapse
 
seytkhanb profile image
Seytkhan • Edited

What if "product-catalog/" has to be dynamic??
Mean:

  1. - pages/
  2. -- something_else
  3. -- [product-catalog]
  4. --- product/
  5. ---- [productid].tsx
Collapse
 
azariaberyl profile image
Azaria Beryl

if you watch the video, I think you add index.js in [product-catalog]/