Next.js Discord

Discord Forum

Load route/page based on API response, rather than by URL (as not known prior to API call)

Unanswered
Manx posted this in #help-forum
Open in Discord
ManxOP
Hi there!

I've got a Django backend that we're trying to use headlessly, but it currently means that I don't know the route (within Next) prior to calling the API - so can't split the code out like the docs would assume.

If I call the API to get any page's data (using the slug) i.e. apiendpoint.com/with-path/about-the-company - it will return data in that response about what component/template/layout (or ideally, Next.js route folder) we will want to use { pageType: "AboutPage", ...}

Currently this URL to view this page would be mysite.com/about-the-company - but we have tonnes of sub-directories, and every single page with completely different page types is currently only accessible to call on this one with-path endpoint.

What's the best way to handle this situation within Next (App router ideally), as apiendpoint.com/with-path/whatever-the-URL-is will need to be called on every single page to return the data from the backend, and somehow make sure code-splitting will still be achieved?

Is it just a case of having at the very top level of the /app having a [slug].tsx file, and then inside that a huge list of ifs in there for every pageType which passes through the API response to every component, to render that page correctly?

if (API.pageType === "AboutPage") {
 return <AboutPage data={API} />
} 

if (API.pageType === "BlogPage") {
 return <BlogPage data={API} />
} 
...


The alternative is we to do a load of 301 redirects (which feels risky?), and make each page template a different API endpoint - so that each route is its own thing apiendpoint.com/about/about-the-company, apiendpoint.com/blog/article-two etc - which would match up far more with how Next.js expects things currently, as each pageType would be a separate route in Next.js

It feels very similar to the issue raised in Nuxt's GitHub issues: https://github.com/nuxt/nuxt/issues/7437

Hope that makes sense! Thanks in advance

0 Replies