Access Browser localStorage in Svelte

- 1 minute read

The browser’s localStorage object is not immediately available in Svelte components. In order to access it, we must wait for our component to be mounted.

Below is a simple Svelte component that sets a localStorage key called foo to a string value of "bar" when a button is pressed.

It also displays the value of foo when the component is mounted and when the button is pressed.

This example uses onMount to wait until the component has been mounted before accessing localStorage:

<script>
    import { onMount } from 'svelte';

    let ls = null;
    let foo = `Cannot read "foo".`;

    const read = () => !!ls && (ls.getItem(`foo`));

    const update = () => {
        !!ls && (ls.setItem(`foo`, `bar`));
        foo = read();
    };

    onMount(() => {
        typeof localStorage !== `undefined` && (ls = localStorage);
        foo = read();
    });
</script>

<p>Value of foo: <samp>{foo}</samp></p>

<button on:click="{update}">Set foo to "bar"</button>

You can also access localStorage from within your stores.

This snippet works interchangeably with sessionStorage.

Link to this section Conclusion

I really hope you found this snippet useful!

I wasted so much time when I was getting started with Svelte by trying to use document, window, and localStorage right away instead of waiting for my components to mount with onMount.