self-taught-man
self-taught-man

Reputation: 21

Nextjs - first level dynamic routing for many pages each of which has children

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.

    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:

  1. 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.
  2. 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.

Upvotes: 2

Views: 2095

Answers (1)

Berci
Berci

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

Related Questions