NextJS App Router中API路由无法获取Cookie的问题求助
我在使用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); }
问题原因
- fetch请求默认不携带Cookie:Layout作为Server Component,发起的fetch请求默认不会自动携带Cookie到同域名的API路由,导致API路由无法读取到Cookie。
- 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
相关产品推荐
相关产品推荐

