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

Next.js 13服务端渲染中如何正确使用Axios withCredentials:true

Next.js 13服务端渲染中Axios withCredentials:true的替代方案

在服务端渲染场景下,Axios的withCredentials:true配置不会生效——因为这个选项是给浏览器设计的,用来控制浏览器是否在跨域请求中自动携带Cookie。而服务端运行时没有浏览器的Cookie存储环境,自然无法通过这个配置完成Cookie传递。

要在服务端实现和客户端withCredentials:true相同的效果,你需要手动从客户端的请求头里提取Cookie,再将其添加到Axios的请求头中:

场景1:App Router 服务端组件/Server Action

在App Router的服务端组件或Server Action中,用next/headers提供的headers()函数获取客户端请求的Cookie:

import axios from 'axios';
import { headers } from 'next/headers';

async function fetchBlogPost(params) {
  // 从客户端请求头中提取Cookie
  const clientCookie = headers().get('cookie');

  const response = await axios.get(`http://localhost:8000/single-blog/${params.slug}`, {
    headers: {
      // 手动将Cookie传递给Axios请求
      Cookie: clientCookie
    }
  });

  return response.data;
}

场景2:Pages Router getServerSideProps

如果是使用Pages Router的getServerSideProps,可以从上下文的req对象中获取Cookie:

import axios from 'axios';

export async function getServerSideProps(context) {
  // 从客户端请求的headers中拿到Cookie
  const clientCookie = context.req.headers.cookie;

  const response = await axios.get(`http://localhost:8000/single-blog/${context.params.slug}`, {
    headers: {
      Cookie: clientCookie
    }
  });

  return {
    props: {
      blog: response.data
    }
  };
}

注意事项

  1. 后端配置要匹配:如果后端和Next.js服务不在同一域名下,后端需要设置Access-Control-Allow-Origin为你的Next.js具体域名(不能是*),同时开启Access-Control-Allow-Credentials: true——既然客户端请求正常,这块应该已经配置完成,但服务端跨域请求也要遵循同样规则。
  2. 关注Cookie的SameSite属性:如果Cookie设置了SameSite=Strict,部分跨域场景下可能无法传递,可根据业务需求调整为Lax或None(设置None时必须搭配Secure,仅HTTPS环境生效)。
  3. 动态获取Cookie:必须从客户端请求头实时提取Cookie,不能硬编码,这样才能对应每个用户的独立会话,避免用户信息混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:45:58