Error when evaluating SSR module /src/stores.js: ReferenceError: localStorage is not defined

Error when evaluating SSR module /src/stores.js: ReferenceError: localStorage is not defined

我正在尝试制作一个在重新加载时存储用户信息的 Svelte 网站。我收到以下错误:

Error when evaluating SSR module /src/stores.js: ReferenceError: localStorage is not defined

重新加载后页面正常加载(包括localStorage.user和localStorage.isLoggedIn),此错误仅在第一次出现。

这是我的 stores.js 文件:

import { writable } from "svelte/store";

const storedUser = JSON.parse(localStorage.user);
export const user = writable(storedUser);
user.subscribe((value) => localStorage.user = JSON.stringify(value));

export const isLoggedIn = writable(localStorage.isLoggedIn === "true");
isLoggedIn.subscribe((value) => localStorage.isLoggedIn = String(value));

如何修复此错误(以及为什么它在重新加载后不显示?)

我意识到在访问 localStorage 之前我必须检查是否有浏览器环境(以为我会 post 这里的答案)。

只需import { browser } from '$app/env';,您可以使用if (browser)

这是我的新 stores.js 文件,应该 至少解决错误:

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

var storedUser = {};
if (browser) {
    storedUser = JSON.parse(localStorage.user);
}
export const user = writable(storedUser);
user.subscribe((value) => {
    if (browser) {
        localStorage.user = JSON.stringify(value);
    }
});

var storedLogin = false;
if (browser) {
    storedLogin = (localStorage.isLoggedIn === "true");
}
export const isLoggedIn = writable(storedLogin);
isLoggedIn.subscribe((value) => {
    if (browser) {
        localStorage.isLoggedIn = String(value);
    }
    
});