在同构SSR框架中,全局直接调用localStorage会因服务端无window对象而报错;需通过typeof window !== 'undefined'守卫或onMounted/useClientOnly等环境判断确保仅在浏览器执行,或封装safeLocalStorage工具统一处理。

在 Nuxt、Next.js 等同构 SSR 框架中,直接在全局作用域(如组件顶层、模块顶层、store 初始化处)调用 localStorage.getItem() 或 sessionStorage.getItem() 会引发编译或服务端渲染报错,根本原因在于:服务端环境没有 window 和 localStorage 对象,Node.js 运行时执行到该语句时会抛出 ReferenceError: localStorage is not defined 或 Cannot read property 'getItem' of undefined。
典型报错表现
这类错误通常出现在构建阶段或 SSR 首次渲染时,而非浏览器端运行时:
-
ReferenceError: localStorage is not defined(最常见) -
ReferenceError: window is not defined(因 localStorage 依赖 window) TypeError: Cannot read properties of undefined (reading 'getItem')- Nuxt 中报
[nuxt] [request error] [unhandled] ReferenceError: localStorage is not defined - Next.js 中报
Error occurred prerendering page "/xxx"+ 上述引用错误
如何快速定位问题代码
重点检查以下位置是否在模块/组件的顶层(非函数内、非生命周期钩子中)直接访问了 localStorage:
- Vue/Nuxt 页面或组件的
<script setup></script>顶层(未包裹在onMounted或if (process.client)中) - React/Next.js 组件的函数体最外层(非
useEffect、非事件回调内) - Pinia/Vuex store 的
state初始化对象中直接读取(如state: () => ({ theme: localStorage.getItem('theme') })) - 工具函数文件(如
utils/storage.js)导出前就执行了localStorage.getItem
正确写法:守卫执行环境
必须确保 localStorage 操作只在浏览器环境中执行。推荐两种安全模式:
HISUI 前端框架基础开发指南。HISUI 是基于 easyui 二次开发的 jQuery UI 组件库,专为医疗信息系统设计。当涉及 HISUI 组件开发、jQuery easyui 表格/表单/布局/窗口、医疗系统前端页面编写时使用此 skill。 涵盖 40 个组件的官方文档参考,支持声明式与编程式两种初始化方式,提供 $cm/$m 数据访问方法。
-
显式环境判断(通用可靠):
if (typeof window !== 'undefined') { const value = localStorage.getItem('key'); } -
框架专属守卫(Nuxt 推荐):
Vue 组件中用onMounted(() => { ... localStorage ... });
Nuxt 3 中可配合useClientOnly或process.client判断:const theme = process.client ? localStorage.getItem('theme') : 'light';
替代方案:封装安全存储工具
避免重复判断,建议统一封装:
export const safeLocalStorage = {
getItem(key) {
if (typeof window === 'undefined') return null;
try {
return localStorage.getItem(key);
} catch {
return null;
}
},
setItem(key, value) {
if (typeof window === 'undefined') return;
try {
localStorage.setItem(key, value);
} catch (e) {
// 忽略 QuotaExceededError 等
}
}
};
后续所有调用都使用 safeLocalStorage.getItem('theme'),无需每次手动判断。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










