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-usNotice: 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
- And this is not possible as we cannot have two folders with brackets on the same level!
- If I hard-code file names of the top-level pages, they worked just fine, however, the problem starts when the user changes their default names (homepage, content, events, ...etc) into something else, NextJS then will have no idea what the pages' structure is yet so it through a 404 not found straight away, as getting the file structure from the API will take few seconds to fetch.
What I have tried:
- middleware: it turned out that we can't fetch data inside middleware.js and if we did, there will be tens of API calls each time the route changes.
- I tried the one dynamic route method, so I fetched the data server-side inside a [wildcard].js file and then based on the data that came back I rewrote the URL to route the requests in the right direction based on the pages types, which is basically the hard-coded page names. That works smoothly but for the top pages not for their children.