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 (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.