Skip to content
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
3 changes: 2 additions & 1 deletion EXAMPLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2197,11 +2197,12 @@ Do realize that this has an impact on the size of the cookie being issued, so it

The `onCallback` hook is run once the user has been redirected back from Auth0 to your application with either an error or the authorization code which will be verified and exchanged.

The `onCallback` hook receives 3 parameters:
The `onCallback` hook receives 4 parameters:

1. `error`: the error returned from Auth0 or when attempting to complete the transaction. This will be `null` if the transaction was completed successfully.
2. `context`: provides context on the transaction that initiated the transaction.
3. `session`: the `SessionData` that will be persisted once the transaction completes successfully. This will be `null` if there was an error.
4. `defaultOnCallback`: the default onCallback hook that would have been called instead of the user-provided hook. This can be used if you want to take an action on callback, but keep the default callback behaviour instead of overriding it.

The hook must return a Promise that resolves to a `NextResponse`.

Expand Down
2 changes: 1 addition & 1 deletion V4_MIGRATION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ import { NextResponse } from 'next/server';
import { Auth0Client } from '@auth0/nextjs-auth0/server';

export const auth0 = new Auth0Client({
async onCallback(error, context, session) {
async onCallback(error, context, session, defaultOnCallback) {
if (error) {
console.error('Authentication error:', error);
return NextResponse.redirect(
Expand Down
30 changes: 20 additions & 10 deletions src/server/auth-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3993,7 +3993,8 @@ ca/T0LLtgmbMmxSv/MmzIg==
expect(mockOnCallback).toHaveBeenCalledWith(
null,
expectedContext,
expectedSession
expectedSession,
expect.any(Function)
);

// validate the session cookie
Expand Down Expand Up @@ -4058,7 +4059,8 @@ ca/T0LLtgmbMmxSv/MmzIg==
expect(mockOnCallback).toHaveBeenCalledWith(
expect.any(Error),
{},
null
null,
expect.any(Function)
);
expect(mockOnCallback.mock.calls[0][0].code).toEqual("missing_state");

Expand Down Expand Up @@ -4137,7 +4139,8 @@ ca/T0LLtgmbMmxSv/MmzIg==
expect(mockOnCallback).toHaveBeenCalledWith(
expect.any(Error),
{},
null
null,
expect.any(Function)
);
expect(mockOnCallback.mock.calls[0][0].code).toEqual("invalid_state");

Expand Down Expand Up @@ -4219,7 +4222,8 @@ ca/T0LLtgmbMmxSv/MmzIg==
responseType: RESPONSE_TYPES.CODE,
returnTo: transactionState.returnTo
},
null
null,
expect.any(Function)
);
expect(mockOnCallback.mock.calls[0][0].code).toEqual(
"authorization_error"
Expand Down Expand Up @@ -4305,7 +4309,8 @@ ca/T0LLtgmbMmxSv/MmzIg==
responseType: RESPONSE_TYPES.CODE,
returnTo: transactionState.returnTo
},
null
null,
expect.any(Function)
);
expect(mockOnCallback.mock.calls[0][0].code).toEqual(
"authorization_code_grant_request_error"
Expand Down Expand Up @@ -4390,7 +4395,8 @@ ca/T0LLtgmbMmxSv/MmzIg==
responseType: RESPONSE_TYPES.CODE,
returnTo: transactionState.returnTo
},
null
null,
expect.any(Function)
);
expect(mockOnCallback.mock.calls[0][0].code).toEqual(
"authorization_code_grant_error"
Expand Down Expand Up @@ -4866,7 +4872,8 @@ ca/T0LLtgmbMmxSv/MmzIg==
expect(mockOnCallback).toHaveBeenCalledWith(
null,
expectedContext,
expectedSession
expectedSession,
expect.any(Function)
);
});

Expand Down Expand Up @@ -4940,7 +4947,8 @@ ca/T0LLtgmbMmxSv/MmzIg==
responseType: RESPONSE_TYPES.CONNECT_CODE,
returnTo: transactionState.returnTo
},
null
null,
expect.any(Function)
);
expect(mockOnCallback.mock.calls[0][0].code).toEqual(
ConnectAccountErrorCodes.MISSING_SESSION
Expand Down Expand Up @@ -5055,7 +5063,8 @@ ca/T0LLtgmbMmxSv/MmzIg==
responseType: RESPONSE_TYPES.CONNECT_CODE,
returnTo: transactionState.returnTo
},
null
null,
expect.any(Function)
);
expect(mockOnCallback.mock.calls[0][0].code).toEqual(
AccessTokenErrorCode.MISSING_REFRESH_TOKEN
Expand Down Expand Up @@ -5173,7 +5182,8 @@ ca/T0LLtgmbMmxSv/MmzIg==
responseType: RESPONSE_TYPES.CONNECT_CODE,
returnTo: transactionState.returnTo
},
null
null,
expect.any(Function)
);
expect(mockOnCallback.mock.calls[0][0].code).toEqual(
ConnectAccountErrorCodes.FAILED_TO_COMPLETE
Expand Down
30 changes: 25 additions & 5 deletions src/server/auth-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,11 @@ export type OnCallbackContext = {
export type OnCallbackHook = (

@Piyush-85 Piyush-85 May 6, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add JSDoc on type parameters, IDEs (VS Code, WebStorm) surface these on hover. Something like below should be good.

/**
 * Hook called once the user has been redirected back from Auth0 to your
 * application's callback route, after the authorization code has been
 * exchanged (or an error has occurred).
 *
 * Return a `NextResponse` to control where the user is sent next.
 * If you do not need custom routing, simply return the result of calling
 * the fourth argument (`defaultOnCallback`) to invoke the SDK's default behaviour.
 *
 * @param error - The error returned from Auth0 or during token exchange.
 *   `null` when the callback completed successfully.
 * @param ctx - Context about the transaction that initiated the auth flow
 *   (e.g. `returnTo` URL, `responseType`, `challengeMode`).
 * @param session - The `SessionData` that will be persisted after a
 *   successful callback. `null` when `error` is present.
 * @param defaultOnCallback - The SDK's built-in callback handler. Call this
 *   to keep the default redirect/error behaviour while still running your own
 *   side effects (e.g. syncing the user to your database, setting extra
 *   cookies). Signature: `(error, ctx) => Promise<NextResponse>`.
 *
 * @example
 * ```ts
 * const auth0 = new Auth0Client({
 *   async onCallback(error, ctx, session, defaultOnCallback) {
 *     if (!error && session) {
 *       await db.upsertUser(session.user); // side effect
 *     }
 *     return defaultOnCallback(error, ctx); // keep default redirect behaviour
 *   }
 * });
 * ```
 */

error: SdkError | null,
ctx: OnCallbackContext,
session: SessionData | null
session: SessionData | null,
defaultOnCallback: (
error: SdkError | null,
ctx: OnCallbackContext
) => Promise<NextResponse>
) => Promise<NextResponse>;

// params passed to the /authorize endpoint that cannot be overwritten
Expand Down Expand Up @@ -676,7 +680,12 @@ export class AuthClient {
state
);
if (!transactionStateCookie) {
return this.onCallback(new InvalidStateError(), {}, null);
return this.onCallback(
new InvalidStateError(),
{},
null,
this.defaultOnCallback

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this.defaultOnCallback is passed as a plain function reference. Since it's a regular method (not an arrow function), this won't be bound when the consumer calls it.
Please use this.defaultOnCallback.bind(this) at each callsite, so if defaultOnCallback ever gets updated to call this.someInternalHelper(), it does not silently break.

);
}

const transactionState = transactionStateCookie.payload;
Expand Down Expand Up @@ -745,7 +754,8 @@ export class AuthClient {
...onCallbackCtx,
connectedAccount
},
session
session,
this.defaultOnCallback
);

await this.transactionStore.delete(res.cookies, state);
Expand Down Expand Up @@ -888,7 +898,12 @@ export class AuthClient {
}
};

const res = await this.onCallback(null, onCallbackCtx, session);
const res = await this.onCallback(
null,
onCallbackCtx,
session,
this.defaultOnCallback
);

// call beforeSessionSaved callback if present
// if not then filter id_token claims with default rules
Expand Down Expand Up @@ -1413,7 +1428,12 @@ export class AuthClient {
req: NextRequest,
state?: string
): Promise<NextResponse> {
const response = await this.onCallback(error, ctx, null);
const response = await this.onCallback(
error,
ctx,
null,
this.defaultOnCallback
);

// Clean up the transaction cookie on error to prevent accumulation
if (state) {
Expand Down