mongodb/node-mongodb-native · error · MongoRuntimeError

Unexpected null serverSession for an explicit session

Error message

Unexpected null serverSession for an explicit session

What it means

Thrown by the `serverSession` getter when a session flagged `explicit` has no underlying `_serverSession` (sessions.ts:217). Explicit sessions acquire a server session eagerly at construction; a null value here indicates internal state corruption. It should not occur under correct usage.

Source

Thrown at src/sessions.ts:218

    this.clusterTime = options.initialClusterTime;

    this.operationTime = undefined;
    this.owner = options.owner;
    this.defaultTransactionOptions = { ...options.defaultTransactionOptions };
    this.transaction = new Transaction();
  }

  /** The server id associated with this session */
  get id(): ServerSessionId | undefined {
    return this.serverSession?.id;
  }

  get serverSession(): ServerSession {
    let serverSession = this._serverSession;
    if (serverSession == null) {
      if (this.explicit) {
        throw new MongoRuntimeError('Unexpected null serverSession for an explicit session');
      }
      if (this.hasEnded) {
        throw new MongoRuntimeError('Unexpected null serverSession for an ended implicit session');
      }
      serverSession = this.sessionPool.acquire();
      this._serverSession = serverSession;
    }
    return serverSession;
  }

  get loadBalanced(): boolean {
    return this.client.topology?.description.type === TopologyType.LoadBalanced;
  }

  /** @internal */
  pin(conn: Connection): void {
    if (this.pinnedConnection) {
      throw TypeError('Cannot pin multiple connections to the same session');

View on GitHub (pinned to 3366c21a63)

Solutions

  1. Update to the latest driver release.
  2. Avoid sharing or reusing a session across concurrent disposal paths.
  3. If it recurs, report a bug with the session lifecycle steps and driver version.
Defensive patterns

Strategy: try-catch

Try / catch

try {
  await session.withTransaction(async () => { /* ... */ });
} catch (e) {
  if (e instanceof MongoRuntimeError && /null serverSession for an explicit session/.test(e.message)) {
    session = client.startSession(); // recreate the explicit session
    return retry();
  }
  throw e;
}

Prevention

When it happens

Trigger: An explicit session whose `_serverSession` was nulled out prematurely; reuse of a session after internal cleanup; a driver bug in session acquisition/release.

Common situations: Driver internal lifecycle bug; concurrent disposal and use of an explicit session; an outdated driver version with a known session-pool regression.

Related errors


AI-assisted analysis of mongodb/node-mongodb-native@3366c21a63 (2026-08-04). Data as JSON: /data/errors/ea116dc6595f5a4c.json. Report an issue: GitHub.