Celso Marques
Celso Marques

Reputation: 418

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

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?

Upvotes: 11

Views: 35194

Answers (3)

Lewis
Lewis

Reputation: 2188

While exsides approach is valid, Sveltekit's recommended approach is;

import { browser } from '$app/environment';

then

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

Upvotes: 2

KaliBoy
KaliBoy

Reputation: 121

hey you need to use onMount

import { onMount } from 'svelte';

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

Upvotes: 12

exside
exside

Reputation: 3884

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
}

Upvotes: 9

Related Questions