Sub topic 7
Supporting Light, Dark and System with localStorage
This chapter turns the dark class from the previous chapters into a three-way theme setting that survives page reloads. It assumes you have a project where dark: utilities already respond to a .dark class on <html>. In Tailwind v3 that means darkMode: 'selector'. In v4 it means the @custom-variant dark rule. It also assumes you know basic DOM scripting and the localStorage API.
Three choices, two outcomes
The page can only be light or dark, but the user has three options:
- Light: always light, whatever the operating system says.
- Dark: always dark.
- System: follow the operating system, including when it changes.
Many sites ship only a light/dark toggle. That locks every user into an explicit choice after their first click. A third option lets them go back to following the system.
| User choice | What is stored | Class on `<html>` |
|---|---|---|
| Light | `theme = "light"` | none |
| Dark | `theme = "dark"` | `dark` |
| System, OS is light | nothing | none |
| System, OS is dark | nothing | `dark` |
Storage holds the user's choice, not the resulting theme. If you saved the resolved result ("dark") when the user picked System, you would lose the information that they wanted to follow the OS.
The storage model: a missing key means system
The simplest model uses the absence of the key to mean "system". There are only two stored values, and "system" is represented by removing the key.
// Run on page load and whenever the user changes the setting
document.documentElement.classList.toggle(
"dark",
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches),
);
// User chooses light mode
localStorage.theme = "light";
// User chooses dark mode
localStorage.theme = "dark";
// User chooses to follow the system again
localStorage.removeItem("theme");The first statement adds dark when either of these is true:
- The saved value is
"dark". - Nothing is saved (
!("theme" in localStorage)) and the OS prefers dark.
If the saved value is "light", both conditions are false, so the class is removed. classList.toggle(name, force) adds the class when force is true and removes it when force is false. Calling it repeatedly is safe, so you never need to check the current state first.
localStorage.theme is property-style access to localStorage.getItem("theme"). It works, but it returns undefined for a missing key, while getItem returns null. The "theme" in localStorage check relies on the property form. Both styles are valid, but don't mix them within one condition.
An alternative is to store "system" explicitly. That makes the stored value self-describing and avoids removeItem. The cost is that you must handle three values everywhere, and any unexpected value needs a fallback. The missing-key model has less state to get wrong, so the rest of this chapter uses it.
Turning the snippet into functions
Inline one-liners are fine for the page-load script, which runs before anything else. The page also needs code that responds to clicks, system changes and storage errors, so split the logic into small functions.
const STORAGE_KEY = "theme";
const media = window.matchMedia("(prefers-color-scheme: dark)");
// Returns "light", "dark" or "system". Never throws.
function readChoice() {
try {
const value = localStorage.getItem(STORAGE_KEY);
return value === "light" || value === "dark" ? value : "system";
} catch {
return "system";
}
}
function writeChoice(choice) {
try {
if (choice === "system") {
localStorage.removeItem(STORAGE_KEY);
} else {
localStorage.setItem(STORAGE_KEY, choice);
}
} catch {
// Storage is unavailable. The choice applies to this page view only.
}
}
function applyTheme(choice) {
const isDark = choice === "dark" || (choice === "system" && media.matches);
document.documentElement.classList.toggle("dark", isDark);
}Three details matter here:
readChoicevalidates the value. If something else wrotetheme = "purple", or an older version of your site stored a different format, the result is"system"instead of a broken state.- Both storage functions are wrapped in
try/catch. AccessinglocalStoragecan throw aSecurityErrorwhen the browser blocks site data, and writes can throw when the quota is exceeded. Some privacy modes behave this way. Without the guard, one exception stops the rest of your script. applyThemetakes a choice and callsmedia.matches, so it always reflects the current OS preference at the moment it runs.
Wiring a three-option control
This markup uses three buttons in a group. Each button has aria-pressed, so assistive technology can announce which one is active, and Tailwind's built-in aria-pressed: variant styles the active one.
<div role="group" aria-label="Theme" class="inline-flex gap-1">
<button
type="button"
data-theme-choice="light"
aria-pressed="false"
class="rounded px-3 py-1 text-sm aria-pressed:bg-gray-900 aria-pressed:text-white dark:text-gray-200 dark:aria-pressed:bg-white dark:aria-pressed:text-gray-900"
>
Light
</button>
<button
type="button"
data-theme-choice="dark"
aria-pressed="false"
class="rounded px-3 py-1 text-sm aria-pressed:bg-gray-900 aria-pressed:text-white dark:text-gray-200 dark:aria-pressed:bg-white dark:aria-pressed:text-gray-900"
>
Dark
</button>
<button
type="button"
data-theme-choice="system"
aria-pressed="false"
class="rounded px-3 py-1 text-sm aria-pressed:bg-gray-900 aria-pressed:text-white dark:text-gray-200 dark:aria-pressed:bg-white dark:aria-pressed:text-gray-900"
>
System
</button>
</div>Here dark:aria-pressed:bg-white is the same variant stacking you saw earlier: it applies only in dark mode and only when the button is pressed. The active button is inverted in each theme so it stays visible.
Add the behavior to the functions above:
function syncButtons(choice) {
document.querySelectorAll("[data-theme-choice]").forEach((button) => {
const pressed = button.dataset.themeChoice === choice;
button.setAttribute("aria-pressed", String(pressed));
});
}
function setTheme(choice) {
writeChoice(choice);
applyTheme(choice);
syncButtons(choice);
}
document.querySelectorAll("[data-theme-choice]").forEach((button) => {
button.addEventListener("click", () => setTheme(button.dataset.themeChoice));
});
// Initial state
const initialChoice = readChoice();
applyTheme(initialChoice);
syncButtons(initialChoice);Load this file with <script src="/theme.js" defer></script> so the buttons exist when it runs. The script sets the class after the page has started to render, so on its own it can still produce a flash of the wrong theme. The next chapter fixes that with a small inline script in <head>. This file then only handles interaction.
Reacting when the system setting changes
When the user picks System, the page should follow the OS if it changes while the page is open. This happens on devices that switch to dark at sunset, or when someone changes the OS setting. The MediaQueryList object you already created fires a change event for this.
media.addEventListener("change", () => {
// Only matters when the user has not made an explicit choice.
// applyTheme already ignores media.matches for "light" and "dark".
applyTheme(readChoice());
});This listener re-reads the stored choice rather than using a variable, so it stays correct even if another tab changed the choice. For an explicit light or dark choice, applyTheme ignores the OS value. The listener is therefore harmless in those cases.
Old Safari versions (before 14) only supported the deprecated media.addListener. Current browsers all support addEventListener on a MediaQueryList.
Keeping several tabs in sync
If the user has two tabs of your site open and changes the theme in one, the other tab stays on the old theme. The browser fires a storage event in every other same-origin tab when localStorage changes. It does not fire in the tab that made the change.
window.addEventListener("storage", (event) => {
// event.key is null when localStorage.clear() was called.
if (event.key === STORAGE_KEY || event.key === null) {
const choice = readChoice();
applyTheme(choice);
syncButtons(choice);
}
});Because removeItem also fires the event, switching back to System in one tab updates the others too. In that case event.newValue is null, which readChoice already treats as System.
The full decision flow
The diagram shows what happens on each trigger. Every path ends in the same applyTheme call.
Reading from one source of truth means each trigger needs only one line of code, and the triggers cannot disagree with each other.
Edge cases
| Situation | What happens | How the code handles it |
|---|---|---|
| Storage blocked or in a restrictive privacy mode | `getItem` or `setItem` throws | `try/catch` falls back to System. The choice lasts for the current page only. |
| Stored value is not `light` or `dark` | An unknown string is saved | `readChoice` returns `"system"`. |
| Another tab changes the setting | Tabs disagree | The `storage` listener re-applies the theme. |
| OS changes while the page is open | System users keep the old theme | The `media` change listener re-applies it. |
| User clears site data | The key disappears | The next load behaves as System. |
| Different subdomains | `localStorage` is per origin | The choice does not carry over to `app.example.com` from `www.example.com`. Use a cookie scoped to the parent domain if you need that. |
The key name is a shared contract between the head script and this file. If you rename it in one place, the two scripts will disagree and the page will flash. If your site shares an origin with other apps, use a more specific key such as "myapp-theme", because every script on the origin can read and overwrite theme.
Summary
- Store the user's choice, not the resolved theme. A missing key means System.
- Keep
readChoice,writeChoiceandapplyThemeas the only places that touch storage and the class. - Validate stored values and guard storage access with
try/catch. - Re-apply the theme on the
mediachange event and on thestorageevent. - Mark the active control with
aria-pressedso that its state is available to assistive technology.
Exercise
A user has chosen Dark, then clicks System. Which localStorage call should the click handler make, and why is it better than saving the string "system"?
Show answer
It should call localStorage.removeItem("theme"). With the missing-key model, a missing key means "follow the system", so only two values (light, dark) ever need validating. Saving "system" also works, but it adds a third stored value that every reader must handle and validate.
Exercise
You open your site in two tabs. In tab A you click Dark. Tab B does not change. Which event and which function call would you add to fix this, and why does tab A not need it?
Show answer
Add a storage event listener on window that, when event.key equals the storage key (or is null), calls readChoice() and passes the result to applyTheme() (and syncButtons() if you have a control). The browser fires storage only in other same-origin tabs, not in the tab that made the change. Tab A already updated itself in its click handler.
Exercise
The user chose System and the OS switches from light to dark at sunset while the page is open. The page stays light. Which part of the script is missing?
Show answer
A change listener on the MediaQueryList returned by window.matchMedia("(prefers-color-scheme: dark)"). It should call applyTheme(readChoice()). Without it, the theme is computed only on page load and when the user clicks.