0

In the Next.js (app router), I have a dynamic route (app/[page]/page) which fetches data from a CMS for each unique page. Among that data, I get a theme. I want to set that theme on the <body>, on the server, so that it is sent to the browser with the pre-rendered HTML.

How do I do that?

Setting the theme on the body specifically is important, so that the whole document gets the correct backgroundColor (otherwise I'd get ugly white backgrounds when I scroll beyond the top or bottom).

It seems to me, the only place to edit the <body> is in the RootLayout. But layouts don't re-render on page transitions, so I can't fetch new data here for each page.

Templates sounds promising with the "will update on each route change"-feature. But from my testing I can't have <html> and <body>-tags in a template. Or rather, if I don't have a RootLayout above it in the tree, Next tells me off and kindly creates one for me.

Updating the classList in a useEffect works, but is not ideal since the pre-rendered HTML might have a different theme, and thus will produce a flicker.

0 Answers0