Next.js 13中如何从React服务端组件向API传递Next-Auth会话
Next.js 13服务端组件调用Next-Auth保护API时传递会话的解决方案
问题原因
服务端组件运行在服务器环境中,发起内部fetch请求时,不会自动携带当前用户的Cookie(这和浏览器发起请求的行为不同)。而你的protected.ts API依赖Cookie中的Next-Auth会话信息来通过getServerSession验证用户,因此直接fetch会导致无法获取session。
解决方案一:复用服务端逻辑(推荐)
既然服务端组件和API都运行在服务端,完全可以跳过网络请求,直接复用API的核心逻辑,这样既高效又避免会话传递问题。
步骤1:提取API核心逻辑到公共模块
创建一个公共函数文件(比如lib/protected-content.ts),把API中的认证和数据返回逻辑抽离出来:
import { getServerSession } from 'next-auth/next'; import { authOptions } from '../app/api/auth/[...nextauth]/route'; export async function getProtectedContent() { // 服务端组件中调用getServerSession无需传入req/res,直接传authOptions即可 const session = await getServerSession(authOptions); if (session) { return { content: 'This is protected content. You can access this content because you are signed in.' }; } return { error: 'You must be signed in to view the protected content on this page.' }; }
步骤2:在服务端组件中调用该函数
import { getProtectedContent } from '@/lib/protected-content'; async function MyServerComponent() { const data = await getProtectedContent(); if (data.content) { console.log('RES:', data.content); } return ( // 组件渲染内容 <div>{data.content || data.error}</div> ); } export default MyServerComponent;
解决方案二:手动传递Cookie到fetch请求
如果必须通过网络请求调用API,可以从服务端组件的请求头中获取Cookie,手动添加到fetch的headers里:
import { headers } from 'next/headers'; async function MyServerComponent() { // 获取当前请求的Cookie头 const cookieHeader = headers().get('cookie'); const res = await fetch('http://localhost:3000/api/protected', { headers: { // 传递Cookie给API请求 cookie: cookieHeader || '', }, }); const json = await res.json(); if (json.content) { console.log('RES:', json.content); } return ( <div>{json.content || json.error}</div> ); } export default MyServerComponent;
这样API就能通过Cookie获取到会话信息,getServerSession可以正常返回用户session。
内容的提问来源于stack exchange,提问作者Jawad
相关产品推荐
相关产品推荐

