Tips, Tricks & Tutorials
Easy Local User Preferences in SvelteKit
Let's look at a super quick way we can get reactive user preferences with Runed!
Prerequisites
This guide is for Svelte version 5 and above. This assumes you have already installed a new SvelteKit project using npx sv create.
Getting Started
To begin, install the Runed package with npm install runed or pnpm add runed. Runed is a collection of Svelte 5 utilities that make reactivity much easier. It handles all the difficult logic for you.
Next, create a userPrefs.js file or whatever name you like. This file should be in the src/lib directory.
Inside of that file, add import { PersistedState } from 'runed'; at the top of the file. Then, create your desired settings as exported variables that create a new PersistedState:
import { PersistedState } from 'runed';
// List all your user settings here
export const showNotifications = new PersistedState("show_notifications", false);
Create your setting toggle and import the states you wish to change:
<script>
import { showNotifications } from '$lib/userPrefs.js';
</script>
<label>
<span>Show Notifications</span>
<input type="checkbox">
</label>
Make the setting always reflect the input element by bind-ing it to that element's value. Usually, that is done with bind:value, but in this case we're using a checkbox, so we need to use bind:checked. It must be bound to the current value, so chain .current onto the variable in the binding.
<script>
import { showNotifications } from '$lib/userPrefs.js';
</script>
<label>
<span>Show Notifications</span>
<input type="checkbox" bind:checked={showNotifications.current}>
</label>
And that's basically it! Now you can import that component into your layout or other settings page/menu so it's always accessible to the user:
<script>
import { ShowNotifications } from '$lib/components/ShowNotifications.svelte';
</script>
<ShowNotifications />
Import the value of the same showNotifications.current or any other setting where you need that value and use it the same way:
<script>
import { showNotifications } from '$lib/userPrefs.js';
</script>
<!-- Should show true/false depending on the checkbox state -->
{showNotifications.current}
Now any time the user clicks the toggle, it will remember the their preferences unless they clear their browser data on each exit.
You can add as many options to the userPrefs.js file as you need! Just export a new variable:
export const blogFont = new PersistedState("blog_font", "inherit");
export const hideSensitiveMedia = new PersistedState("hide_sensitive_media", true);