Light and dark theme toggle button for Next JS

Next JS together with SSR can be a challenge to create a flicker-free toggle button for light and dark, but a session cookie can help.


 by  tuedodev

Mar 2024

This boilerplate for Next JS aims to integrate a toggle button in the header of the website and to make this state persistent via an encrypted session token (which can be extended with further session attributes such as the user name or email address).

Since the setting of a session cookie is already GDPR-relevant in some countries, a simple cookie consent banner is used, which in turn links to the website's privacy policy. Intercepting and Parallel Routes from Next JS are used for the privacy policy modal.

This boilerplate goes a slightly different way than described in the excellent article by Salma Alam-Naylor with the use of the browser's localStorage functionality Finally, Next JS makes it very easy to read the cookie in the middleware via the request object and return the update via response. In the layout component, the theme value can be inserted into the data-theme of the html tag.

Light or dark theme: Choose a source of truth

The problem with setting the theme lies in what you use as the source of truth if some parameters are not set (take the system settings, the prefers-color-scheme). Once you have made a decision here, the next challenge is which theme to set for the first rendering.

If you read the localStorage of the browser on the client side, for example, or the system settings and reset the theme accordingly, SSR can lead to hydration warnings because the DOM on the client side suddenly no longer matches the virtual DOM on the server side. Some people try to work around this error with suppressHydrationWarning, but given the triviality of the problem, this seems excessive to me and somehow doesn't feel right.

This boilerplate tries to avoid the problem by setting a fallback constant, i.e. a theme that takes effect if other system settings and preferences are not available (in this case it is dark mode).

Cookie Consent and Privacy Policy Handling

Because we are opting for session cookies here, which are already GDPR-relevant in some countries, a simple cookie consent mechanism is set via the <dialog> tag, which is now widely supported by browsers. A link takes you to a privacy policy that uses parallel and interception routing from Next JS.

This feature of Next JS makes it possible to use a modal that returns to the original page when going back, but goes to the privacy policy route in the root directory when the user reloads the page in the browser.

Github Repository of the Code

Live-Demo on Vercel

This post has not been commented on yet.

Add a comment