Next.js
getServerSession
팁
authOptions를 전달할 필요 없이 도우미 함수를 생성할 수 있습니다:
auth.ts
import type { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from "next"
import type { NextAuthOptions } from "next-auth"
import { getServerSession } from "next-auth"
// `app/api/auth/[...nextauth]/route.ts`에서 `NextAuth`에 전달할 필요가 있는 것을 가져와야 합니다
export const config = {
providers: [], // 나머지 구성
} satisfies NextAuthOptions
// 서버 컨텍스트에서 사용
export function auth(
...args:
| [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"]]
| [NextApiRequest, NextApiResponse]
| []
) {
return getServerSession(...args, config)
}
서버 측에서 호출할 때, 즉 라우트 핸들러, 리액트 서버 컴포넌트, API 라우트 또는 getServerSideProps에서 session 객체를 검색하기 위해 getSession 대신 이 함수를 사용하는 것을 권장합니다. 이 방법은 특히 NextAuth.js를 데이터베이스와 함께 사용할 때 유용합니다. 이 방법은 서버 측에서 getSession보다 응답 시간을 극적으로 줄일 수 있는데, 이는 추가적인 API 라우트로의 fetch를 피할 수 있기 때문입니다(이는 일반적으로 Next.js에서 권장되지 않습니다). 또한, getServerSession은 callbacks.jwt 또는 callbacks.session이 무언가를 변경한 경우 쿠키 만료 시간을 올바르게 업데이트하고 세션 내용을 업데이트합니다.
getServerSession은 NextAuth.js를 초기화할 때 NextAuth에 전달할 동일한 객체를 전달해야 합니다. 이를 위해 다음과 같이 NextAuth.js 옵션을 내보낼 수 있습니다:
[...nextauth].ts에서:
import NextAuth from "next-auth"
import type { NextAuthOptions } from "next-auth"
export const authOptions: NextAuthOptions = {
// 구성 설정
}
export default NextAuth(authOptions)