Reputation: 21
Nextjs - first level dynamic routing for many pages each of which has children
I have a NextJS 12.2/React 18 app linked to a CMS, where users can set up their custom page structure, content & theme.
In the front-end, there will be some API calls to get the app settings and configuration including the page hierarchy.
The default six top-level page names are homepage, content, events, user, search and blog.
We can think of these six pages as types, so we have six different types, and users can change the names of these types but not the type itself. And as you may expect, changing the names will change the URL segment accordingly.
Four of those six types can have child-page(s), multi-level (nested). Here are some examples of what the default app's URLs can look like:
mydomain.com/homepage mydomain.com/content/ mydomain.com/events/by-location/[locationID] mydomain.com/events/[eventID] mydomain.com/events/by-category/[catLevelOne] mydomain.com/user/profile mydomain.com/blog/[postID] mydomain.com/search?term=searchterm mydomain.com/contact-us
Notice: there is also a static page "contact-us" which is not connected to the CMS.
To achieve this model within the NextJS methodology of routing, the app file structure should look like this (if it is allowed):
pages
├── [blog]
│ ├── [postID].js
│ └── index.js
├── [content]
│ ├── [levelOne]
│ │ ├── [levelTwo]
│ │ │ ├── [levelThree]
│ │ │ │ └── index.js
│ │ │ └── index.js
│ │ └── index.js
│ └── index.js
├── [events]
│ ├── by-category
│ │ ├── [catLevelOne]
│ │ │ ├── [catLevelTwo]
│ │ │ │ └── index.js
│ │ │ └── index.js
│ │ └── index.js
│ ├── by-location
│ │ ├── [location]
│ │ │ ├── [locationID].js
│ │ │ └── index.js
│ │ └── index.js
│ ├── index.js
│ └── [eventID].js
├── [user]
│ ├── account.js
│ ├── emailverification.js
│ ├── password.js
│ └── register.js
├── search.js
└── homepage.js
What I have tried:
Upvotes: 2
Views: 2095
Reputation: 3386
I know I am late to the party but in case someone still needs this, I think you were very close. Using shallow-routing with your second approach should do the job. Basically add [...wildcard].js
and
based on the data that comes back, rewrote the URL to route the requests in the right direction based on the pages types
A good idea would be to do this in the getServerSideProps function since you can make requests there, it will be faster, and you don't have to worry about any glitch when the page loads.
Also in case anyone has any doubts:
Of course we can't have two folders with brackets on the same level
because if you have [id1]
and [id2]
how will the nextJS know what mydomain.com/1234
should be? There is now way to tell if 1234
is id1
or id2
.
I think the last part is probably obvious, but still... In case anyone wonders.
Upvotes: 1