mongodb/node-mongodb-native · error · MongoOIDCError

Attempted to get an access token when none exists.

Error message

Attempted to get an access token when none exists.

What it means

Internal invariant of TokenCache (token_cache.ts:27): getAccessToken() was called while accessToken is undefined. The OIDC workflows always gate getAccessToken() behind hasAccessToken, so a normal public-API call path should never reach this throw. Reaching it indicates a regression in cache-state management inside the driver or direct misuse of the @internal TokenCache API. It surfaces as MongoDriverError (the local MongoOIDCError subclass extends MongoDriverError).

Solutions

  1. If reached via the public API, file a driver bug with a reproduction (the public workflows guard this)
  2. If you use the internal TokenCache API directly, always check cache.hasAccessToken before cache.getAccessToken()
  3. Upgrade to the latest driver version in case it is a fixed regression

Example fix

// before (internal misuse)
const token = cache.getAccessToken();

// after
const token = cache.hasAccessToken ? cache.getAccessToken() : undefined;
Defensive patterns

Strategy: type-guard

Type guard

function getAccessTokenSafe(cache: TokenCache): string | undefined {
  return cache.hasAccessToken ? cache.getAccessToken() : undefined;
}

Prevention

When it happens

Trigger: Calling the internal TokenCache.getAccessToken() directly without first checking hasAccessToken; or a driver code path that calls getAccessToken() without its hasAccessToken guard (a bug). Not reachable through the documented public MongoClient API.

Common situations: Forking or monkeypatching the driver's auth providers and bypassing the hasAccessToken check. Hitting a driver regression where a workflow calls getAccessToken after removeAccessToken in an edge case.

Related errors


AI-assisted analysis of mongodb/node-mongodb-native@dce7939f86 (2026-08-11). Data as JSON: /api/errors/ab063953e8f7eadd. Report an issue: GitHub.

Appendix: source

Thrown at src/cmap/auth/mongodb_oidc/token_cache.ts:27

  private refreshToken?: string;
  private idpInfo?: IdPInfo;
  private expiresInSeconds?: number;

  get hasAccessToken(): boolean {
    return !!this.accessToken;
  }

  get hasRefreshToken(): boolean {
    return !!this.refreshToken;
  }

  get hasIdpInfo(): boolean {
    return !!this.idpInfo;
  }

  getAccessToken(): string {
    if (!this.accessToken) {
      throw new MongoOIDCError('Attempted to get an access token when none exists.');
    }
    return this.accessToken;
  }

  getRefreshToken(): string {
    if (!this.refreshToken) {
      throw new MongoOIDCError('Attempted to get a refresh token when none exists.');
    }
    return this.refreshToken;
  }

  getIdpInfo(): IdPInfo {
    if (!this.idpInfo) {
      throw new MongoOIDCError('Attempted to get IDP information when none exists.');
    }
    return this.idpInfo;
  }

View on GitHub (pinned to dce7939f86)