Next.js Discord

Discord Forum

Send over raw data used on page in <head>

Answered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
Hi all, author of LINCD.js here. A JavaScript library to work with RDF (aka structured data / linked data) with reusable components tied to specific schemas.

We want to try to switch from our custom node.js backend to next.js but I have one question about one of our needs that I'm wondering if it will be possible at all with next.js:

On each first page request, we are currently collecting all the data that is used by components on the page whilst it is rendered in the backend, and we send that data in JSON-LD format to the frontend, injected in the <head> tag.

The frontend reads that data and builds the graph back up in local memory. The local graph is then used for other pages. (If some required data is already locally available it will not be reloaded)

My question is: is it possible to do something like this with next.js? Possibly with getServerSideProps (?) Or middleware? Any pointers in the right direction would be much appreciated
Answered by Asian black bear
The new useServerInsertedHTML hook might be a good fit, even though it is conceived mostly for styles https://nextjs.org/docs/app/building-your-application/styling/css-in-js#configuring-css-in-js-in-app
View full answer

5 Replies

Asian black bear
@Asiatic Lion Do you have any interest in using the /app router in the future or are you tied to /pages?
Asian black bear
The new useServerInsertedHTML hook might be a good fit, even though it is conceived mostly for styles https://nextjs.org/docs/app/building-your-application/styling/css-in-js#configuring-css-in-js-in-app
Answer
Asian black bear
In the pages router, the _document.tsx file does render once to provide the static "shell" around your React app. They actually have docs on customizing it with SSR dynamic-ish data: https://nextjs.org/docs/pages/building-your-application/routing/custom-document#customizing-renderpage
Both of these methods are for css-in-js mostly, but your use pattern sounds almost exactly the same.
Asiatic LionOP
Great, thanks so much @Cape lionbot, that's a great starting point for me to explore from.