Cookie Store for SvelteKit

March 27, 2024

Cookie Store for SvelteKit

Table of Contents

Dependencies

This script uses the js-cookie package to manage cookies. The theme switcher example has additional dependencies.

bash
pnpm add js-cookie

The Store

cookieStore is a writeable store that will automatically update the cookie whenever the store is updated.

serverGetCookie is a function that should be called from the load function of a page/layout server route.

Usage

The initial value should be set from the cookie if it already exists. Get the cookie from the server for SSR and set the initial value to the cookie value in the layout.

svelte
<script lang="ts">
	import { cookieStore } from "$server/cookie";
	import { setContext } from "svelte";

	export let data;

	// data.app is the value of the cookie, if it exists
	$: app = setContext("app", cookieStore("app", data.app));
</script>

Example: Creating a Theme Switcher with DaisyUI

Dependencies

The theme switcher uses the @sveltekit-addons/document package to change the <html> tag’s data-theme and class attributes.

The @sveltekit-addons/document package provides a preprocessor that allows you to modify the <html> and <body> tags from any page or layout. For setup instructions, see the documentation.

bash
pnpm add -D @sveltekit-addons/document

Setup

The App.Cookie type is used to define the cookie structure in the implementation. app.settings.theme is of type Themes, which is a union of the available theme names, and app.settings.mode is of type ThemeGroups, which is a union of "dark" | "light".

Implementation

The themes in constants.ts correspond to the themes configured in the DaisyUI plugin. The ThemeSwitcher component will allow the user to select a theme from the available themes. If the theme is set to "system", the theme and mode will be set based on the user’s system preference and update accordingly. Otherwise, mode will be set based on the theme’s group.