Skip to content

Commit a307079

Browse files
balazsorban44ThangHuuVu
andauthoredNov 24, 2022
fix(ts): improve unstable_getServerSession return type (#5792)
Co-authored-by: Thang Vu <hi@thvu.dev>
1 parent d52b7a6 commit a307079

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed
 

‎packages/next-auth/src/next/index.ts

+22-12
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type {
99
} from "next"
1010
import type { NextAuthOptions, Session } from ".."
1111
import type {
12+
CallbacksOptions,
1213
NextAuthAction,
1314
NextAuthRequest,
1415
NextAuthResponse,
@@ -90,17 +91,25 @@ export default NextAuth
9091

9192
let experimentalWarningShown = false
9293
let experimentalRSCWarningShown = false
93-
export async function unstable_getServerSession(
94+
95+
type GetServerSessionOptions = Partial<Omit<NextAuthOptions, "callbacks">> & {
96+
callbacks?: Omit<NextAuthOptions['callbacks'], "session"> & {
97+
session?: (...args: Parameters<CallbacksOptions["session"]>) => any
98+
}
99+
}
100+
101+
export async function unstable_getServerSession<
102+
O extends GetServerSessionOptions,
103+
R = O["callbacks"] extends { session: (...args: any[]) => infer U }
104+
? U
105+
: Session
106+
>(
94107
...args:
95-
| [
96-
GetServerSidePropsContext["req"],
97-
GetServerSidePropsContext["res"],
98-
NextAuthOptions
99-
]
100-
| [NextApiRequest, NextApiResponse, NextAuthOptions]
101-
| [NextAuthOptions]
108+
| [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"], O]
109+
| [NextApiRequest, NextApiResponse, O]
110+
| [O]
102111
| []
103-
): Promise<Session | null> {
112+
): Promise<R | null> {
104113
if (!experimentalWarningShown && process.env.NODE_ENV !== "production") {
105114
console.warn(
106115
"[next-auth][warn][EXPERIMENTAL_API]",
@@ -128,7 +137,8 @@ export async function unstable_getServerSession(
128137

129138
let req, res, options: NextAuthOptions
130139
if (isRSC) {
131-
options = args[0] ?? { providers: [] }
140+
options = Object.assign({}, args[0], { providers: [] })
141+
132142
// eslint-disable-next-line @typescript-eslint/no-var-requires
133143
const { headers, cookies } = require("next/headers")
134144
req = {
@@ -143,7 +153,7 @@ export async function unstable_getServerSession(
143153
} else {
144154
req = args[0]
145155
res = args[1]
146-
options = args[2]
156+
options = Object.assign(args[2], { providers: [] })
147157
}
148158

149159
options.secret ??= process.env.NEXTAUTH_SECRET
@@ -173,7 +183,7 @@ export async function unstable_getServerSession(
173183
if (status === 200) {
174184
// @ts-expect-error
175185
if (isRSC) delete body.expires
176-
return body as Session
186+
return body as R
177187
}
178188
throw new Error((body as any).message)
179189
}

0 commit comments

Comments
 (0)
Please sign in to comment.