Skip to content
Latchkey

MongoDB "MongoServerError: Authentication failed" in CI

MongoDB accepted the connection and rejected authentication. The username/password is wrong, or the client authenticated against the wrong authSource database. The server is reachable - this is deterministic and will not pass on retry.

What this error means

A driver call fails with "MongoServerError: Authentication failed" (error code 18). It fails the same way every run because the credentials or authSource are wrong.

psql
MongoServerError: Authentication failed.
    code: 18,
    codeName: 'AuthenticationFailed'

Common causes

Wrong username/password

The credentials in the connection string differ from MONGO_INITDB_ROOT_USERNAME/MONGO_INITDB_ROOT_PASSWORD on the service.

Wrong authSource

Root users authenticate against admin. Omitting ?authSource=admin (or pointing it at the app database) makes auth fail.

How to fix it

Set credentials and authSource

Match the connection string to the service credentials and the correct auth database.

.github/workflows/ci.yml
services:
  mongo:
    image: mongo:7
    env:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: ${{ secrets.MONGO_PASSWORD }}
env:
  MONGO_URL: mongodb://root:${{ secrets.MONGO_PASSWORD }}@127.0.0.1:27017/app?authSource=admin

Verify the secret and auth database

  1. Confirm the password secret is non-empty and the name matches.
  2. Use authSource=admin for the root user created by the image.
  3. Create an app-scoped user if you prefer to authenticate against the app database.

How to prevent it

  • Keep Mongo credentials in one secret used by the service and the URL.
  • Always set the correct authSource.
  • Retrying will not fix an authentication failure - it is deterministic; fix credentials/authSource.

Frequently asked questions

What causes ""MongoServerError: Authentication failed""?
The credentials in the connection string differ from MONGO_INITDB_ROOT_USERNAME/MONGO_INITDB_ROOT_PASSWORD on the service.
How do I fix "MongoServerError: Authentication failed"?
Match the connection string to the service credentials and the correct auth database.

Related guides

References

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