DEV Community

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

delanyobott profile image
delanyo {Yokoyama} agbenyo

localStorage is not defined. Error

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.

kudadam profile image
Lucretius Biah

In sveltekit, you can check if the piece of code is running on the server or browser, you just have to import the browser variable from the env and then use an if statement to run your code. So it should be something like this

import { browser } from "$app/env";

if (browser){
    variable.subscribe((value) => localStorage.user = JSON.stringify(value))
Enter fullscreen mode Exit fullscreen mode
cepiherd profile image

this code is running in my code , thank you ,appreciated

danawoodman profile image
Dana Woodman

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)

ryanfiller profile image

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