Skip to content

beforeSessionSaved behaves differently when called after login or after token refresh #2370

@wolfgangGoedel

Description

@wolfgangGoedel

Checklist

Description

The beforeSessionSaved() hook is provided with the user and the tokenSet after login. I am using the accessToken to call my resource-server to authorize and enrich the session – and I'm removing the idToken from the final session to reduce the cookie size.

When refreshing the session via getAccessToken(), the beforeSessionSaved() hook is called with the outdated tokenSet though and ignores any modification applied to it. This prevents me from calling my resource-server because I can't use the updated accessToken and from removing the idToken.

It might be the desired behavior not to be able to modify the tokenSet in beforeSessionSaved() in which case the modification should not be possible after login (in handleCallback).

It would be great if you could clarify the intended behavior please before I can eventually propose a fix.

Reproduction

Difficult to reproduce because it involves token refresh - but the following unit-test of server/client.ts in describe("getAccessToken", ...) fails with my expectations

    it("should provide the refreshed accessToken to beforeSessionSaved hook", async () => {
      let accessToken: string | undefined;
 
      // should not be necessary, but there is a bug in initialization     
      mockGetTokenSet.mockResolvedValue([
        null,
        { tokenSet: mockRefreshedTokenSet }
      ]);

      client = new Auth0Client({
        beforeSessionSaved: async (session) => {
          accessToken = session.tokenSet?.accessToken;
          return session;
        }
      });

      const mockReq = { headers: new Headers() } as NextRequest;
      const mockRes = new NextResponse();

      await client.getAccessToken(mockReq, mockRes, { refresh: true });

      expect(accessToken).toBe("new_access_token");
    });

Additional context

No response

nextjs-auth0 version

4.11.0

Next.js version

15.4.1

Node.js version

20.19.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions