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

Next.js 13中Middleware获取LocalStorage数据失败求助

问题原因及解决方案

你的核心问题是:Next.js的Middleware运行在服务器端(Edge Runtime),而localStorage是浏览器端独有的API,服务器环境中不存在window对象,所以你的getLocalStorage函数会直接返回null,根本拿不到数据。

解决方案:改用Cookie存储数据

Cookie会在每次HTTP请求时自动携带到服务器,Middleware可以通过req.cookies直接读取,这是服务器端获取客户端状态的标准方式。

步骤1:替换LocalStorage工具函数为Cookie工具函数

创建lib/cookies.ts文件,替换原有的localStorage.ts:

export const setCookie = (key: string, value: string, days = 7) => {
  if (typeof window !== 'undefined') {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    const expires = `expires=${date.toUTCString()}`;
    document.cookie = `${key}=${value}; ${expires}; path=/; SameSite=Lax`;
  }
};

export const getCookie = (key: string): string | null => {
  if (typeof window !== 'undefined') {
    const name = `${key}=`;
    const decodedCookie = decodeURIComponent(document.cookie);
    const ca = decodedCookie.split(';');
    for(let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) === ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) === 0) {
        return c.substring(name.length, c.length);
      }
    }
  }
  return null;
};

export const removeCookie = (key: string) => {
  if (typeof window !== 'undefined') {
    document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
  }
};

步骤2:修改Middleware代码,从Cookie读取数据

更新middleware.ts,直接通过req.cookies获取加密数据:

import { key, timeEncryptKey, tokenEncryptKey, userEncryptKey } from '@/lib/cryptoJs/encrypt'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export async function middleware(req: NextRequest) {
  try {
    // 从请求Cookie中获取加密后的token和session数据
    const dataToken = req.cookies.get(tokenEncryptKey)?.value;
    const dataSession = req.cookies.get(timeEncryptKey)?.value;
    
    if (dataSession) {
      const sessionData = parseInt(CryptoJS.AES.decrypt(dataSession, key).toString(CryptoJS.enc.Utf8), 10);
      console.log(sessionData);
    } else {
      console.log('未在Cookie中找到会话数据');
    }
  } catch (error) {
    console.error('处理Token时出错:', error);
  }
}

步骤3:客户端存储逻辑替换

把你原本调用setLocalStorage的地方,换成setCookie即可,用法和之前一致。

注意事项

  • Cookie单条存储容量限制约4KB,不要存储过大的数据
  • 敏感数据务必保持加密(你已经在做AES加密,这点没问题)
  • Cookie的SameSite属性建议设为Lax或Strict,避免跨站请求伪造风险
  • 客户端读取数据时,使用getCookie替代原有的getLocalStorage

内容的提问来源于stack exchange,提问作者naonimmmmid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:18:35