Home >Web Front-end >JS Tutorial >Setting Up Themes in SSR React Applications

Setting Up Themes in SSR React Applications

Patricia Arquette
Patricia ArquetteOriginal
2025-01-06 00:56:38581browse

Setting Up Themes in SSR React Applications

Imagine visiting a website that seamlessly adapts to your preferences—effortlessly switching between light, dark and system-based themes.

This article continues my series on SSR with React. In the basics article, we explored production-ready configurations, while in advanced techniques, we tackled challenges like hydration errors. Now, we’ll take it a step further by implementing robust theming support that integrates seamlessly with SSR.

Table of Contents

  • Themes and SSR
  • Implementation
    • Install Dependencies
    • Add cookie to the Server Build
    • Apply Themes on the Server
    • Handle Themes on the Client
  • Conclusion

Themes and SSR

The main issue is the Initial Flash of Incorrect Theme (FOIT).

Essentially, themes are just about changing CSS variables. In most cases, you’ll work with three themes:

  • Light: The default set of CSS variables.
  • Dark: Applied when the tag has the class dark.
  • System: Automatically switches based on the user's system preference, using the (prefers-color-scheme: dark) media query to determine if the theme should be dark or light.

By default, the server will render the HTML with the light theme and send it to the browser. If a user prefers the dark theme, they will see a visible theme change on the first page load, which disrupts the user experience.

There are two main ways to solve this issue:

  • Add a