DEV Community

loading...

Discussion on: πŸš€ Svelte Quick Tip: Connect a store to local storage

Collapse
delanyobott profile image
delanyo {Yokoyama} agbenyo

localStorage is not defined. Error

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
Collapse
danawoodman profile image
Dana Woodman Author

Where are you running this? If it is in SvelteKit localStorage won't be defined so you'll have to only use the store in the browser as documented in the Kit docs (see "browser" variable)

Collapse
kenkunz profile image
Ken Kunz

I got the same error while migrating an app to SvelteKit. The FAQ states this is due to how Vite processes imports (even with SSR disabled). See "How do I use a client-side only…" in SvelteKit FAQ as well as Issue #754 True SPA mode.

For now, I was able to get this working by disabling SSR on the page that depends on localStorage and importing & globally registering node-localstorage before importing the lib that depends on localStorage.

import 'node-localstorage/register';
import { storable } from 'svelte-storable';
Enter fullscreen mode Exit fullscreen mode

The register endpoint in node-localstorage does not overwrite localStorage if it already exists, so you still get the native browser implementation.