DEV Community

Discussion on: 🚀 Svelte Quick Tip: Connect a store to local storage

Collapse
 
ryanfiller profile image
ryanfiller

I'm doing this in Sapper, I haven't made the switch to Sveltekit yet, so take the with a grain of salt.

I was able to get it work by doing a typeof check and skipping the subscription during SSR.

// stores/user.js

import { writable } from 'svelte/store'
export const user = writable()

// check for localStorage, this won't run on SSR
if (typeof localStorage !== 'undefined') {
  user.subscribe((value) => localStorage.user = JSON.stringify(value))
}
Enter fullscreen mode Exit fullscreen mode