Table of Contents
Add Darkmode to sveltekit
How to add darkmode to a sveltekit project
hooks.server.ts
import type { Handle } from '@sveltejs/kit';
import { sequence } from '@sveltejs/kit/hooks';
const darkMode: Handle = async ({ event, resolve }) => {
const darkModeCookie = event.cookies.get('darkmode') === 'true';
const response = await resolve(event, {
transformPageChunk: ({ html }) => html.replace('%darkmode%', darkModeCookie ? 'dark' : '')
});
return response;
};
export const handle = sequence(darkMode);
app.html
<body class="%darkmode%"></body>
If you are using tailwind edit the following config
app.css
@custom-variant dark (&:where(.dark, .dark *));
ToggleDarkmode.svelte
<script>
import { onMount } from 'svelte';
let isDarkMode = $state(false);
function toggleDarkMode() {
isDarkMode = !isDarkMode;
document.cookie = `darkmode=${isDarkMode};path=/`;
document.body.classList.toggle('dark', isDarkMode);
}
onMount(() => {
isDarkMode = document.cookie.includes('darkmode=true');
document.body.classList.toggle('dark', isDarkMode);
});
</script>
<button onclick={toggleDarkMode}>
{isDarkMode ? '🌙' : '☀️'}
</button>
Now the body element is gonna have the dark class once the cookie is set.
Related snippets
Sveltekit page store
How to use the sveltekit page store to access url parameters
Create images from HTML
How to convert html to an image on the server as a sveltekit API endpoint
CSS breakout button
How to make an entire card clickable without nested links
Discord oAuth with Sveltekit
How to log in to a website with discord