{"id":"3748464d166937fc","repo":"mongodb/node-mongodb-native","slug":"authcontext-must-provide-credentials-374846","errorCode":null,"errorMessage":"AuthContext must provide credentials.","messagePattern":"AuthContext must provide credentials\\.","errorType":"exception","errorClass":"MongoMissingCredentialsError","httpStatus":null,"severity":"critical","filePath":"src/cmap/auth/scram.ts","lineNumber":32,"sourceCode":"\ntype CryptoMethod = 'sha1' | 'sha256';\n\nclass ScramSHA extends AuthProvider {\n  cryptoMethod: CryptoMethod;\n\n  constructor(cryptoMethod: CryptoMethod) {\n    super();\n    this.cryptoMethod = cryptoMethod || 'sha1';\n  }\n\n  override async prepare(\n    handshakeDoc: HandshakeDocument,\n    authContext: AuthContext\n  ): Promise<HandshakeDocument> {\n    const cryptoMethod = this.cryptoMethod;\n    const credentials = authContext.credentials;\n    if (!credentials) {\n      throw new MongoMissingCredentialsError('AuthContext must provide credentials.');\n    }\n\n    const nonce = await randomBytes(24);\n    // store the nonce for later use\n    authContext.nonce = nonce;\n\n    const request = {\n      ...handshakeDoc,\n      speculativeAuthenticate: {\n        ...makeFirstMessage(cryptoMethod, credentials, nonce),\n        db: credentials.source\n      }\n    };\n\n    return request;\n  }\n\n  override async auth(authContext: AuthContext) {","sourceCodeStart":14,"sourceCodeEnd":50,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/cmap/auth/scram.ts#L14-L50","documentation":"Thrown by ScramSHA.prepare() (scram.ts:32) as a MongoMissingCredentialsError when the AuthContext has no credentials object at the start of the SCRAM handshake's speculative authentication phase. The driver needs username/password to build the first SCRAM message. This almost always indicates the connection string or credentials resolver did not supply authentication details for an auth-enabled deployment.","triggerScenarios":"Connecting with a URI that omits username/password (e.g. 'mongodb://host:27017') against a deployment with authentication enabled; or MongoClient.connect with an authMechanism=MONGODB-SCRAM-SHA-1|256 but a credentials callback that resolved undefined. Also fires if the AuthContext was constructed programmatically without a MongoCredentials instance.","commonSituations":"Switching from a no-auth local MongoDB to an auth-enabled Atlas/replica set without updating the URI; environment-specific credentials not loaded (e.g. dotenv not applied before connect); typo'd authSource that yields empty credentials; credentials provider returning undefined in multi-tenant setups.","solutions":["Add username:password@ to the connection string: 'mongodb://user:pass@host:27017/?authSource=admin'","Verify the authSource matches where the user is defined (commonly 'admin' or '$external')","If using options.auth, pass a MongoCredentials-like object with username and password","Confirm environment variables (MONGODB_URI, DB_USER, DB_PASS) are loaded before MongoClient construction"],"exampleFix":"// before\nconst client = new MongoClient('mongodb://host:27017');\n// after\nconst client = new MongoClient('mongodb://user:pass@host:27017/?authSource=admin');","handlingStrategy":"validation","validationCode":"function hasAuthCredentials(uri: string): boolean {\n  try {\n    const parsed = new URL(uri);\n    return Boolean(parsed.username && parsed.password);\n  } catch {\n    return false;\n  }\n}\n// before connect:\nif (!hasAuthCredentials(process.env.MONGODB_URI!) && serverRequiresAuth) {\n  throw new Error('MONGODB_URI missing username/password for auth-enabled deployment');\n}","typeGuard":"function isCompleteCredentials(c: { username?: unknown; password?: unknown }): c is { username: string; password: string } {\n  return typeof c.username === 'string' && typeof c.password === 'string' && c.password.length > 0;\n}","tryCatchPattern":"try {\n  await client.connect();\n} catch (e) {\n  if (e instanceof MongoMissingCredentialsError) {\n    // fix the connection string / auth option, then re-create the client\n  }\n  throw e;\n}","preventionTips":["Validate the connection string has credentials before constructing MongoClient","Centralize URI building in one config module that asserts username/password are present","In CI, assert MONGODB_URI contains credentials against an auth-enabled fixture"],"tags":["auth","scram","credentials","connection-string"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}