Next.js Discord

Discord Forum

Dynamic styles/css from database while still retaining sever side rendering from App directory?

Unanswered
Northern snakehead posted this in #help-forum
Open in Discord
Northern snakeheadOP
Is there a way to dynamically set some CSS in the <head> via <style> in the app router? I assume this could be in done pages router as we had access to <Head> which we now don't have in app router.

I've got page styles saved to the users theme in the database and on particular page load I want to apply this theming without any page/css flashing and loading on the client side.

Since I can't pass anything to the layout file I feel like potentially my only option is to pull <html> and <body> out of my layout and directly into the page possibly unless there's an alternative solution.

generateMetadata() has no styling option

37 Replies

where the theme of page comes from cms (api request)
so one page is full blue, one is full white for example
possible with App router
so i would make it ISR if you can or
I have this inside layout.js
<script
          dangerouslySetInnerHTML={{
            __html: `
              try {
                    if (localStorage.getItem("theme") != null && localStorage.getItem("theme") === 'true') {
                        document.documentElement.classList.add('theme-dark')
                    } else {
                        document.documentElement.classList.remove('theme-dark')
                    }
                } catch (_) {}
            `,
          }}
        >
</script> 
this is simple logic to control theme with 0 flash of colours 🙂
Northern snakeheadOP
lets say I have multiple users, which have all picked different background colors for their page
so it's not just a case of "dark" or "light"
Northeast Congo Lion
yep i would do thus
set up ur themes using html variable
so what i did was pass a bunch of theme variables to a wrapper div
html
  body
    div.wrapper.blue-white (apply --colours here)
Northern snakeheadOP
ok so you essentially removed the theming process from the body and into your wrapper
Northeast Congo Lion
so in ur css u can have:
.wrapper {
 &.blue-white {
   --colours: red
 }

 &.blue-red {
   --colours: blue
 }
}
correct
Northern snakeheadOP
yeah I was trying to do it at body level, but maybe I just cant
as you can see
this is a site i have worked on.
no flash
theme of blue/white is controlled at server (content management) level
Northern snakeheadOP
wrapper it is then
Northeast Congo Lion
screenshot is inside Skeleton.jsx
then this is how it looks at page.js level
because data/page is server component
we have theme value as pre-rendered' basically
so no flash 🙂
Northern snakeheadOP
yeah that's what I'm after
shame I can't get access to the head though, would of made my life easier ha
Northeast Congo Lion
trust
Northern snakeheadOP
thanks for the tip
Northeast Congo Lion
no worries if u cant get it wortking
just holla at me