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

Next.js 15中间件读取Cookie中JWT Token始终返回undefined,偶现正常

解决Next.js 15中间件无法稳定读取JWT Cookie的问题

针对你遇到的中间件多数情况下读取jwtToken Cookie返回undefined的问题,下面是几个常见原因和对应的解决方法:

1. Cookie的路径(Path)设置错误

如果登录时设置Cookie的Path不是根路径/,而是某个特定路径(比如/login),那么当请求/api/invoices这类其他路径时,浏览器不会携带该Cookie,导致中间件无法读取。

解决办法:
设置Cookie时指定Path: '/',确保所有路径都能访问到该Cookie。示例代码(登录接口中):

const response = NextResponse.json({ success: true });
response.cookies.set({
  name: 'jwtToken',
  value: '你的JWT令牌',
  path: '/', // 必须设置为根路径
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'lax',
  maxAge: 86400 // 1天有效期
});
return response;

2. SameSite属性配置不合理

如果Cookie的SameSite设置为Strict,当请求是从其他页面跳转或跨域发起时,浏览器可能不会携带Cookie。而None属性需要配合Secure使用(仅HTTPS环境有效),否则Cookie不会生效。

解决办法:

  • 同站请求设置SameSite: 'lax'(大多数场景推荐)
  • 跨域请求设置SameSite: 'none'并开启secure: true(仅生产HTTPS环境)

3. Secure属性与环境不匹配

如果生产环境未开启Secure,或者本地开发(HTTP)开启了Secure,都会导致Cookie无法被正确携带。

解决办法:
根据环境动态设置Secure:

secure: process.env.NODE_ENV === 'production'

4. 请求未携带Credentials

如果前端通过fetch或axios发起请求时,未设置credentials选项,浏览器不会自动携带Cookie。

解决办法:
发起请求时添加credentials: 'include':

// fetch示例
fetch('/api/invoices', {
  method: 'GET',
  credentials: 'include'
});

// axios示例
axios.get('/api/invoices', {
  withCredentials: true
});

5. 排查中间件与Cookie名称一致性

确保代码中读取的Cookie名称jwtToken和登录时设置的名称完全一致(大小写敏感),避免因拼写错误导致无法读取。

6. 临时调试:打印所有Cookie

在中间件中打印所有Cookie,确认jwtToken是否存在,帮助定位问题:

export async function middleware(request: NextRequest) {
  console.log('所有Cookie:', request.cookies.getAll());
  const jwtToken = request.cookies.get("jwtToken");
  const token = jwtToken?.value;

  console.log('读取到的Token:', token);

  if (!token) {
    return NextResponse.json(
      { message: "no token provided, access denied from middleware" },
      { status: 401 }
    );
  }
  return NextResponse.next();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:19:56