session - NextJs 受 Next Auth 保护的 API
问题描述
我在使用 NextAuth 构建 NextJs Web 时遇到问题。我在 pages/api 中创建了自己的 API,并使用 NextAuth 的 getSession 对其进行保护。当我使用 getServerSideProps 或 getStaticProps 调用 API 时,getSession 返回一个空值,但当我在组件函数内部调用 API 时,getSession 返回用户数据值。任何人都可以提供帮助或有任何提示吗?
页面/index.jsx
export async function getStaticProps(context) {
const projects = await fetchApi(`${process.env.BASE_URL}/projects`);
console.log(projects)
return {
props: {},
};
}
页面/api/项目
import { getSession } from 'next-auth/client';
async function handler(req, res) {
const projectService = new ProjectService();
let session;
let emailUser;
try {
session = await getSession({ req });
console.log(session); // null
emailUser = session.user.email;
if (!session) {
throw new AuthenticationError('No authenticated');
}
} catch (error) {
if (error instanceof ClientError) {
return res.status(error.statusCode).json(clientErrRes(error));
}
return res.status(500).json(serverErrRes(error));
}
...another code
}
解决方案
您需要在上下文中的 fetch 中添加标头。因为你是从服务器端获取的。
const {req}=context
const {cookie} = req.headers
return fetch(`${process.env.BASE_URL}/projects`, {
headers: {
'Cookie':cookie
}
})