Next.js Discord

Discord Forum

Dynamic Routing with Specific Subpages in App Router

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Hi,

I have a route where I need 5 distinct subpages (page1 to page5). Functionally, these subpages are identical - the only difference being the data they fetch. However, their respective subpages vary greatly in content and functionality but should have the same name (/page1/new, /page2/new etc).

While I can generalize page1 to page5 using dynamic routes ([page]), I then hit a wall when trying to add specific subpages under each dynamic route. For instance, having a "new" page at /page1/new and /page2/new wont work since I then would have to create 5 folders called "new" in the dynamic route and they would be indistinguishable as routes. Something I can do is to go backwards in path for new, for example using (/new/page1 and /new/page2 etc). However, this also feels like a bad solution since that would create weird navigation URL wise, moving from /page1 to /new/page1.

However, If I simply decide not to use a dynamic route I instead get the problem where I have to create 5 identical page.tsx files for the 5 pages (page1 to page5) which is code duplication and looks like a really ugly solution.

So my question is, which of these is the best solution to the problem? or is there an even better solution I'm just not aware off? This sounds like a really common problem which hopefully has a elegant solution I'm not aware of, Thanks.

My Solutions:
1. Dynamic Route with swapped URL elements:
- Use a dynamic route for the main pages and when it comes to specific subpages, swap order of URL elements making the root route specific (new instead of [page]).
- Drawback: I'm not a fan of how the URL elements swap places (/page1 to /new/page1 compared to the usual /page1 to /page1/new).

2. Distinct Pages:
- Create individual pages for page1 to page5 and avoid dynamic routing altogether.
- Drawback: Leads to code duplication, given that the 5 pages are identical except for the fetched data.

0 Replies