Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save smc181002/99b24fcc634f89400df0b30141b236e6 to your computer and use it in GitHub Desktop.
Save smc181002/99b24fcc634f89400df0b30141b236e6 to your computer and use it in GitHub Desktop.
Using localStoage with sveltekit and svelte store

About

I have been building sveltekit and I enocuntered this where sveltekit wont work if you use localstorage API directly because our sveltekit will be running in both client and server and server node.js will pose an error for undefined localStoage API

I have looked for this in stackoverflow and I was not able to find the exact answer anywhere. But then I encountered a stackoverflow question after a lot of searching and here is the solution

import { writable } from 'svelte/store';
import { browser } from '$app/env'; 

// let isLoggedIn
let isLogged;
if (browser) {
  const isLoggedIn= localStorage.getItem("isLoggedIn");

  isLogged = writable(isLoggedIn);
  isLogged.subscribe(value => {
    localStorage.setItem("isLoggedIn", value);
  })
}
export {isLogged};

we are using the browser variable from $app/env provided by sveltekit and with this we can know if the code is being executed in server or client and we can use localstoage peacefully

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment