Skip to content
Latchkey

MongoDB "Authentication failed" (SCRAM) with MONGODB_URI in CI

The server rejected the SCRAM handshake: the credentials in your connection string did not match a user. The network is fine; the username, password, or authSource is wrong or not injected.

What this error means

The driver throws "MongoServerError: Authentication failed" right after connecting, once it tries to authenticate with the credentials from MONGODB_URI.

node
MongoServerError: Authentication failed.
    at Connection.onMessage (/app/node_modules/mongodb/lib/cmap/connection.js:229:30) {
  code: 18,
  codeName: 'AuthenticationFailed'
}

Common causes

The password secret is empty or wrong

The CI secret holding the password is unset or stale, so the URI carries no valid credentials and SCRAM fails.

The wrong authSource database

The user lives in admin (or a specific db) but the URI omits or misnames authSource, so the server checks the wrong database.

How to fix it

Build the URI from injected secrets with authSource

  1. Store the username and password as CI secrets.
  2. Compose the URI including authSource for the database that holds the user.
  3. URL-encode any special characters in the password.
.github/workflows/ci.yml
env:
  MONGODB_URI: mongodb://${{ secrets.MONGO_USER }}:${{ secrets.MONGO_PASS }}@localhost:27017/appdb?authSource=admin

Verify the user exists in the expected db

Confirm the credentials authenticate against the intended authSource before running tests.

Terminal
mongosh "$MONGODB_URI" --eval 'db.runCommand({connectionStatus:1})'

How to prevent it

  • Inject credentials from secrets, never hardcode them in the URI.
  • Set authSource to the database that owns the user (often admin).
  • URL-encode special characters in passwords.

Frequently asked questions

What causes ""Authentication failed.""?
The CI secret holding the password is unset or stale, so the URI carries no valid credentials and SCRAM fails.
How do I fix "Authentication failed."?
Build the URI from injected secrets with authSource

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card