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

NextJS App Router中API路由无法获取Cookie的问题求助

问题:Next.js App Router API路由无法获取Cookie中的accessToken

我在使用Next.js App Router时,遇到API路由无法从Cookie获取accessToken的问题,具体代码和场景如下:

相关代码情况

API路由代码(/api/profile/route.ts)

import { NextResponse } from "next/server";
import { cookies } from "next/headers";

const getCookie = async (name: string) => {
 return cookies().get(name)?.value ?? "";
};

export async function GET(request) {
 const token = await getCookie("accessToken");  
 console.log(token); // 此处无法输出token
 return NextResponse.json(user.data, { status: 200 });
}

Layout中调用API的代码

const test123 = await fetch("http://localhost:3000/api/profile");

Layout中直接获取Cookie的代码(可成功)

...
import { cookies } from "next/headers";

const getCookie = async (name: string) => {
 return cookies().get(name)?.value ?? "";
};

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
 const token = await getCookie("accessToken");
 console.log(token) // 此处可成功输出token

 return (
   ...
  );
}

后端设置Cookie的代码(NestJS)

async login(@Body() loginDto: LoginDto, @Response() res: ExpressResponse) {
    const loginRes = await this.authService.login(loginDto.token);

    res.cookie('accessToken', loginRes?.accessToken, {
      expires: new Date(new Date().getTime() + 1 * 60 * 60 * 1000), // 1小时
      sameSite: 'strict',
      httpOnly: true,
    });

    return res.send(loginRes);
}

问题原因

  1. fetch请求默认不携带Cookie:Layout作为Server Component,发起的fetch请求默认不会自动携带Cookie到同域名的API路由,导致API路由无法读取到Cookie。
  2. SameSite严格限制:后端设置的sameSite: 'strict'会进一步限制Cookie的发送场景,无Cookie的请求自然无法获取到值。

解决方案

方案1:修改fetch请求,强制携带Cookie

在Layout的fetch调用中添加credentials: 'include'(同域名场景也可用'same-origin'),让请求携带Cookie:

const test123 = await fetch("http://localhost:3000/api/profile", {
  credentials: 'include'
});

方案2:直接传递Token到API(更高效)

既然Layout已经能获取到Token,可直接将Token通过请求头传递给API,避免重复读取Cookie:

// Layout中的代码
const token = await getCookie("accessToken");
const test123 = await fetch("http://localhost:3000/api/profile", {
  headers: {
    'Authorization': `Bearer ${token}`
  }
});
// API路由中的代码
export async function GET(request) {
 const authHeader = request.headers.get('authorization');
 const token = authHeader?.split(' ')[1] ?? '';
 console.log(token);
 // 后续业务逻辑
 return NextResponse.json(user.data, { status: 200 });
}

方案3:调整Cookie的SameSite设置(可选)

若业务允许,可以将后端Cookie的sameSite改为'lax',但strict的安全性更高,优先推荐前两个方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 15:46:25