
Next.js 애플리케이션에서 getServerSession을 사용하려고 할 때 다음과 같은 오류가 발생
Error: `headers` was called outside a request scope.
import { connectDB } from "@/util/database";
import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "../auth/[...nextauth]";
export default async function BookMarkChkHandler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
const session = getServerSession(authOptions); // 문제 발생 부분
const db = (await connectDB()).db('trip');
console.log('session', session);
await db.collection('bookmark').insertOne(req.body);
res.status(200).json({ msg: 'success' });
}
}
getServerSession은 API 라우트에서 사용될 때 req와 res를 인자로 받음.
그러나 위의 코드에서는 getServerSession(authOptions)처럼 호출하여, 요청 정보를 전달하지 않아 오류가 발생.
const session = getServerSession(authOptions); // 문제 발생 부분
부분을
const session = await getServerSession(req, res, authOptions);
로 변경함으로써 해결!
getServerSession은
const session = await getServerSession(req, res, authOptions);
const session = await getServerSession(authOptions);