title: Prevent page flash in Next.js 12 with Tailwind CSS class-based dark mode
body: <p>How can one prevent the page flash when using class-based dark mode in Tailwind CSS with Next.js v12 without using any 3rd party pkgs like next-themes?</p>
  <p>I've looked at:</p>
  <ul>
  <li>this Q&amp;A <a href="https://stackoverflow.com/questions/67094919/how-to-fix-dark-mode-background-color-flicker-in-nextjs">How to fix dark mode background color flicker in NextJS?</a> and while it's a valid/working solution in Next.js &lt;v12, in v12 it no longer works and throws warnings in dev which suprisingly turn to a build blocking error in prod env
  <code>Do not add &lt;script&gt; tags using next/head (see inline &lt;script&gt;). Use next/script instead.  See more info here: https://nextjs.org/docs/messages/no-script-tags-in-head-component</code></li>
  <li>This article <a href="https://www.vidyasource.com/blog/dark-mode-nextjs-tailwindcss-react-hooks" rel="nofollow noreferrer">https://www.vidyasource.com/blog/dark-mode-nextjs-tailwindcss-react-hooks</a> however including the script <code>&lt;Script strategy=&quot;beforeInteractive&quot; src=&quot;/scripts/darkMode.js&quot;/&gt;</code> still results in a page flash as it adds <code>defer</code> to it in the <code>head</code></li>
  <li>This official Tailwind CSS dark mode doc on what's required <a href="https://tailwindcss.com/docs/dark-mode#toggling-dark-mode-manually" rel="nofollow noreferrer">https://tailwindcss.com/docs/dark-mode#toggling-dark-mode-manually</a></li>
  </ul>
  <pre class="lang-js prettyprint-override"><code>// On page load or when changing themes, best to add inline in `head` to avoid FOUC
  if (localStorage.theme === 'dark' || (!('theme' in localStorage) &amp;&amp; window.matchMedia('(prefers-color-scheme: dark)').matches)) {
      document.documentElement.classList.add('dark')
  } else {
      document.documentElement.classList.remove('dark')
  }
  </code></pre>
  <p>I think they restrict putting things in <code>Head</code> from v12 to prepare for Suspense / Streaming / React v18.</p>
  <p>Either way, I'm lost on how to do it without next-themes, does anyone know how can we just inject that bit of script to prevent that page flash?</p>
  <p>Hope this question makes sense, if not, please give me a shout.</p>
  <p>I like simple and minimalistic things, hence the aim to reduce the dependency on 3rd party pkgs, such a simple thing should be possible without overcomplicated solution IMO.</p>