TailwindCSS dark mode can't change <html> or add class="dark" tag on production. How to solve this issue?

Updated: Feb 10, 2025

TailwindCSS dark mode can't change <html> or add class="dark" tag on production. How to solve this issue?

TailwindCSS dark mode relies on adding the dark class to the <html> tag or the <body> tag to enable dark mode styling across the entire website. However, in production environments, it might not be possible to modify the HTML tag directly due to various reasons such as security concerns, content delivery networks (CDNs), or static site generators.

To solve this issue, there are a few workarounds that you can consider:

  1. Use a JavaScript solution: You can write a small JavaScript code snippet that checks if the user has enabled dark mode in their browser settings and adds the dark class to the <html> or <body> tag accordingly. This approach works well for websites that are not heavily reliant on server-side rendering.

Here's an example of how to implement this solution using plain JavaScript:

if (matchMedia('(prefers-color-scheme: dark)').matches) {
  document.documentElement.classList.add('dark');
}

You can add this code to a <script> tag in the <head> section of your HTML file or include it in an external JavaScript file.

  1. Use a server-side solution: If your website relies heavily on server-side rendering, you can modify the HTML tag on the server-side before sending it to the client. This approach works well for static site generators and server-side rendered applications.

For example, in Next.js, you can modify the _app.js file to add the dark class to the <html> tag based on the user's preference:

import { useEffect } from 'react';
import { useRouter } from 'next/router';

function MyApp({ Component, pageProps }) {
  const router = useRouter();

  useEffect(() => {
    if (matchMedia('(prefers-color-scheme: dark)').matches) {
      document.documentElement.classList.add('dark');
    }
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp;
  1. Use a middleware solution: If you're using a framework like Express.js or Nuxt.js, you can use middleware to modify the HTML tag before sending it to the client. This approach works well for server-side rendered applications.

For example, in Express.js, you can create a middleware function to add the dark class to the <html> tag based on the user's preference:

app.use((req, res, next) => {
  if (req.headers['x-forwarded-proto'] === 'https') {
    if (matchMedia('(prefers-color-scheme: dark)').matches) {
      res.locals.htmlClass = 'dark';
    }
  }
  next();
});

You can then use this htmlClass variable in your HTML templates to conditionally add the dark class to the <html> tag.

These are just a few of the possible solutions to enable TailwindCSS dark mode in production environments without modifying the <html> tag directly. The best approach depends on your specific use case and the technologies you're using.