Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(jwt): allow getToken in Server Components #5791

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions apps/dev/app/server-component/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
import { unstable_getServerSession } from "next-auth/next"

export default async function Page() {
const session = await unstable_getServerSession()
return <pre>{JSON.stringify(session, null, 2)}</pre>
const { token, ...session } = await unstable_getServerSession({
providers: [],
callbacks: {
session: ({ session, token }) => ({ ...session, token }),
},
})

return (
<>
<h2>Session</h2>
<pre>{JSON.stringify(session, null, 2)}</pre>
<h2>Token</h2>
<pre>{JSON.stringify(token, null, 2)}</pre>
</>
)
}
11 changes: 6 additions & 5 deletions packages/next-auth/src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { init } from "./init"
import { assertConfig } from "./lib/assert"
import { SessionStore } from "./lib/cookie"

import type { NextAuthAction, NextAuthOptions } from "./types"
import type { NextAuthAction, NextAuthOptions, Session } from "./types"
import type { Cookie } from "./lib/cookie"
import type { ErrorType } from "./pages/error"
import { parse as parseCookie } from "cookie"
Expand Down Expand Up @@ -39,9 +39,9 @@ export interface OutgoingResponse<
cookies?: Cookie[]
}

export interface NextAuthHandlerParams {
export interface NextAuthHandlerParams<S extends Session> {
req: Request | RequestInternal
options: NextAuthOptions
options: NextAuthOptions<S>
}

async function getBody(req: Request): Promise<Record<string, any> | undefined> {
Expand Down Expand Up @@ -78,8 +78,9 @@ async function toInternalRequest(
}

export async function NextAuthHandler<
Body extends string | Record<string, any> | any[]
>(params: NextAuthHandlerParams): Promise<OutgoingResponse<Body>> {
Body extends string | Record<string, any> | any[],
S extends Session = Session
>(params: NextAuthHandlerParams<S>): Promise<OutgoingResponse<Body>> {
const { options: userOptions, req: incomingRequest } = params

const req = await toInternalRequest(incomingRequest)
Expand Down
10 changes: 5 additions & 5 deletions packages/next-auth/src/core/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ import { createCSRFToken } from "./lib/csrf-token"
import { createCallbackUrl } from "./lib/callback-url"
import { RequestInternal } from "."

import type { InternalOptions } from "./types"
import type { InternalOptions, Session } from "./types"

interface InitParams {
interface InitParams<S extends Session = Session> {
host?: string
userOptions: NextAuthOptions
userOptions: NextAuthOptions<S>
providerId?: string
action: InternalOptions["action"]
/** Callback URL value extracted from the incoming request. */
Expand All @@ -29,7 +29,7 @@ interface InitParams {
}

/** Initialize all internal options and cookies. */
export async function init({
export async function init<S extends Session>({
userOptions,
providerId,
action,
Expand All @@ -38,7 +38,7 @@ export async function init({
callbackUrl: reqCallbackUrl,
csrfToken: reqCsrfToken,
isPost,
}: InitParams): Promise<{
}: InitParams<S>): Promise<{
options: InternalOptions
cookies: cookie.Cookie[]
}> {
Expand Down
6 changes: 3 additions & 3 deletions packages/next-auth/src/core/lib/assert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { defaultCookies } from "./cookie"

import type { RequestInternal } from ".."
import type { WarningCode } from "../../utils/logger"
import type { NextAuthOptions } from "../types"
import type { NextAuthOptions, Session } from "../types"

type ConfigError =
| MissingAPIRoute
Expand All @@ -39,8 +39,8 @@ function isValidHttpUrl(url: string, baseUrl: string) {
*
* REVIEW: Make some of these and corresponding docs less Next.js specific?
*/
export function assertConfig(params: {
options: NextAuthOptions
export function assertConfig<S extends Session>(params: {
options: NextAuthOptions<S>
req: RequestInternal
}): ConfigError | WarningCode[] {
const { options, req } = params
Expand Down
6 changes: 3 additions & 3 deletions packages/next-auth/src/core/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createHash } from "crypto"

import type { NextAuthOptions } from "../.."
import type { InternalOptions } from "../types"
import type { InternalOptions, Session } from "../types"
import type { InternalUrl } from "../../utils/parse-url"

/**
Expand All @@ -28,8 +28,8 @@ export function hashToken(token: string, options: InternalOptions<"email">) {
* If no secret option is specified then it creates one on the fly
* based on options passed here. If options contains unique data, such as
* OAuth provider secrets and database credentials it should be sufficent. If no secret provided in production, we throw an error. */
export function createSecret(params: {
userOptions: NextAuthOptions
export function createSecret<S extends Session>(params: {
userOptions: NextAuthOptions<S>
url: InternalUrl
}) {
const { userOptions, url } = params
Expand Down
12 changes: 8 additions & 4 deletions packages/next-auth/src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export type { LoggerInstance }
*
* [Documentation](https://next-auth.js.org/configuration/options#options)
*/
export interface NextAuthOptions {
export interface NextAuthOptions<S extends Session = Session> {
/**
* An array of authentication providers for signing in
* (e.g. Google, Facebook, Twitter, GitHub, Email, etc) in any order.
Expand Down Expand Up @@ -97,7 +97,7 @@ export interface NextAuthOptions {
*
* [Documentation](https://next-auth.js.org/configuration/options#callbacks) | [Callbacks documentation](https://next-auth.js.org/configuration/callbacks)
*/
callbacks?: Partial<CallbacksOptions>
callbacks?: Partial<CallbacksOptions<Profile, Account, S>>
/**
* Events are asynchronous functions that do not return a response, they are useful for audit logging.
* You can specify a handler for any of these events below - e.g. for debugging or to create an audit log.
Expand Down Expand Up @@ -256,7 +256,11 @@ export interface Profile {
}

/** [Documentation](https://next-auth.js.org/configuration/callbacks) */
export interface CallbacksOptions<P = Profile, A = Account> {
export interface CallbacksOptions<
P = Profile,
A = Account,
S extends Session = Session
> {
/**
* Use this callback to control if a user is allowed to sign in.
* Returning true will continue the sign-in flow.
Expand Down Expand Up @@ -319,7 +323,7 @@ export interface CallbacksOptions<P = Profile, A = Account> {
session: Session
user: User | AdapterUser
token: JWT
}) => Awaitable<Session>
}) => Awaitable<S>
/**
* This callback is called whenever a JSON Web Token is created (i.e. at sign in)
* or updated (i.e whenever a session is accessed in the client).
Expand Down
32 changes: 16 additions & 16 deletions packages/next-auth/src/next/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ import type {
NextAuthResponse,
} from "../core/types"

async function NextAuthNextHandler(
async function NextAuthNextHandler<S extends Session>(
req: NextApiRequest,
res: NextApiResponse,
options: NextAuthOptions
options: NextAuthOptions<S>
) {
const { nextauth, ...query } = req.query

Expand Down Expand Up @@ -60,18 +60,18 @@ async function NextAuthNextHandler(
return res.send(handler.body)
}

function NextAuth(options: NextAuthOptions): any
function NextAuth(
function NextAuth<S extends Session>(options: NextAuthOptions<S>): any
function NextAuth<S extends Session>(
req: NextApiRequest,
res: NextApiResponse,
options: NextAuthOptions
options: NextAuthOptions<S>
): any

/** The main entry point to next-auth */
function NextAuth(
function NextAuth<S extends Session>(
...args:
| [NextAuthOptions]
| [NextApiRequest, NextApiResponse, NextAuthOptions]
| [NextAuthOptions<S>]
| [NextApiRequest, NextApiResponse, NextAuthOptions<S>]
) {
if (args.length === 1) {
return async (req: NextAuthRequest, res: NextAuthResponse) =>
Expand All @@ -85,17 +85,17 @@ export default NextAuth

let experimentalWarningShown = false
let experimentalRSCWarningShown = false
export async function unstable_getServerSession(
export async function unstable_getServerSession<S extends Session>(
...args:
| [
GetServerSidePropsContext["req"],
GetServerSidePropsContext["res"],
NextAuthOptions
NextAuthOptions<S>
]
| [NextApiRequest, NextApiResponse, NextAuthOptions]
| [NextAuthOptions]
| [NextApiRequest, NextApiResponse, NextAuthOptions<S>]
| [NextAuthOptions<S>]
| []
): Promise<Session | null> {
): Promise<S | null> {
if (!experimentalWarningShown && process.env.NODE_ENV !== "production") {
console.warn(
"[next-auth][warn][EXPERIMENTAL_API]",
Expand All @@ -121,7 +121,7 @@ export async function unstable_getServerSession(
experimentalRSCWarningShown = true
}

let req, res, options: NextAuthOptions
let req, res, options: NextAuthOptions<S>
if (isRSC) {
options = args[0] ?? { providers: [] }
// eslint-disable-next-line @typescript-eslint/no-var-requires
Expand All @@ -143,7 +143,7 @@ export async function unstable_getServerSession(

options.secret = options.secret ?? process.env.NEXTAUTH_SECRET

const session = await NextAuthHandler<Session | {} | string>({
const session = await NextAuthHandler<S | {} | string, S>({
options,
req: {
host: detectHost(req.headers["x-forwarded-host"]),
Expand All @@ -162,7 +162,7 @@ export async function unstable_getServerSession(
if (status === 200) {
// @ts-expect-error
if (isRSC) delete body.expires
return body as Session
return body as S
}
throw new Error((body as any).message)
}
Expand Down
9 changes: 6 additions & 3 deletions packages/next-auth/src/next/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface NextAuthMiddlewareOptions {
* ---
* [Documentation](https://next-auth.js.org/configuration/pages)
*/
pages?: NextAuthOptions["pages"]
pages?: NextAuthOptions<any>["pages"]

/**
* You can override the default cookie names and options for any of the cookies
Expand All @@ -38,7 +38,7 @@ export interface NextAuthMiddlewareOptions {
*/
cookies?: Partial<
Record<
keyof Pick<keyof NextAuthOptions["cookies"], "sessionToken">,
keyof Pick<keyof NextAuthOptions<any>["cookies"], "sessionToken">,
Omit<CookieOption, "options">
>
>
Expand Down Expand Up @@ -146,7 +146,10 @@ async function handleMiddleware(

// the user is not logged in, redirect to the sign-in page
const signInUrl = new URL(`${basePath}${signInPage}`, origin)
signInUrl.searchParams.append("callbackUrl", `${basePath}${pathname}${search}`)
signInUrl.searchParams.append(
"callbackUrl",
`${basePath}${pathname}${search}`
)
return NextResponse.redirect(signInUrl)
}

Expand Down