How can I fix "sessionStorage is not defined" in Svelte?

Viewed 15481

I'm new in Svelte and I'm trying to set some info into sessionStorage but it is throwing "sessionStorage is not defined". I realised that I received this error because it's running on the server side.

I created a component at /src/components/nav.svelte that uses /src/domain/auth/service.js and the error occurs in the last one.

Searching on the web I found that in this case I must use sessionStorage inside onMount function. Is that the right way?

How can I avoid that my code get a little mess?

2 Answers

hey you need to use onMount

import { onMount } from 'svelte';

onMount(() => {
    sessionStorage.setItem('myWork', 'Developer');
});

You could try to check if you're actually in a browser environment, e.g. something like

if (window && window.sessionStorage) {
    // do your stuff with sessionStorage
}

or

if (typeof window !== 'undefined') {
    // do your stuff with sessionStorage
}
Related