You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt.js SSR模式下localStorage is not defined 500错误求助

解决Nuxt.js SSR模式下localStorage is not defined的500错误

问题根源

  1. 全局中间件在模块顶层直接执行了isAuthenticated(),SSR模式下这段代码会在服务端运行,而服务端环境不存在浏览器的localStorage对象,直接调用触发错误。
  2. isAuthenticated函数未区分客户端/服务端环境,直接访问localStorage。

修复方案

方案1:使用Nuxt内置useLocalStorage(推荐)

Nuxt的useLocalStorage会自动兼容SSR环境,服务端运行时不会访问浏览器存储,同时把认证判断逻辑移到中间件函数内部,避免模块顶层提前执行。

修改auth.global.js代码:

import { defineNuxtRouteMiddleware, navigateTo, useLocalStorage } from "nuxt/app";
import axios from "axios";

async function isAuthenticated() {
    // useLocalStorage自动处理SSR,第二个参数是默认值
    const token = useLocalStorage('token', '')
    if (!token.value) {
        return false;
    }
    try {
        const res = await axios.get("/user", {
            headers: {
                Authorization: `Bearer ${token.value}`,
                token: token.value,
            },
        });
        return res.status === 200;
    } catch (err) {
        return false;
    }
}

export default defineNuxtRouteMiddleware(async(to, from) => {
    // 将认证判断移到中间件内部,确保请求时才执行
    const isAuth = await isAuthenticated()
    
    const isDashboardRoute = /^\/dashboard/.test(to.fullPath);
    if (isDashboardRoute && !isAuth) {
        return navigateTo("/auth/login");
    }
    if (to.fullPath === "/auth/login" && isAuth) {
        return navigateTo("/dashboard");
    }
    if (to.fullPath === "/auth/register" && isAuth) {
        return navigateTo("/dashboard");
    }
});

方案2:手动判断客户端环境

如果不想用Nuxt组合式API,可手动判断当前运行环境,仅在客户端访问localStorage,同时调整认证逻辑执行时机:

import { defineNuxtRouteMiddleware, navigateTo } from "nuxt/app";
import axios from "axios";

async function isAuthenticated() {
    let token = null
    // 仅在客户端环境访问localStorage
    if (process.client) {
        token = localStorage.getItem("token")
    }
    if (!token) {
        return false;
    }
    try {
        const res = await axios.get("/user", {
            headers: {
                Authorization: `Bearer ${token}`,
                token: token,
            },
        });
        return res.status === 200;
    } catch (err) {
        return false;
    }
}

export default defineNuxtRouteMiddleware(async(to, from) => {
    const isAuth = await isAuthenticated()
    
    const isDashboardRoute = /^\/dashboard/.test(to.fullPath);
    if (isDashboardRoute && !isAuth) {
        return navigateTo("/auth/login");
    }
    if (to.fullPath === "/auth/login" && isAuth) {
        return navigateTo("/dashboard");
    }
    if (to.fullPath === "/auth/register" && isAuth) {
        return navigateTo("/dashboard");
    }
});

额外优化建议

  • Nuxt中推荐使用内置的$fetch或useFetch替代直接引入axios,它们会自动处理baseURL和SSR环境下的请求适配。
  • 若需要服务端也能获取认证状态,可改用useCookie存储token,更适配SSR场景的认证逻辑。

内容的提问来源于stack exchange,提问作者داود خانی

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:07:07