Mongoose cannot sign in to MongoDB Atlas: bad auth, authentication failed
MongoServerError: bad auth : Authentication failed.Short answer
Authentication failed means the server rejected the user in your connection string. For Atlas, use a database user, not your Atlas login, and check the name, the password and the cluster. Percent-encode special characters in the password, and set the right authSource. Test the string in mongosh before the app.
Fix it fast
1Find out which cause you have
Take the connection string out of the app and try it alone. If mongosh rejects it too, the problem is the string or the user, not your code. Keep the password in quotes.
mongosh "mongodb+srv://<user>:<password>@<cluster>.mongodb.net/test"2Match what you see, then jump to its fix
- 1
bad auth right after the first connection attempt, in every environmentWrong user, wrong password or wrong clusterFix - 2
The password contains characters such as @ : / ? # % ! or a space,Special characters in the password are not percent-encodedFix - 3
The user exists and the password is right, but the string has a database name in the path and no authSourceThe authSource database is wrongFix
- 1
What does the error look like?
MongoServerError: bad auth : Authentication failed.MongoError: bad auth Authentication failed.
Cause 1 of 3
Wrong user, wrong password or wrong cluster
1Check
Atlas needs a MongoDB database user, created for the cluster. It is not your Atlas account. Compare user, password and cluster host with the user list of the project.
echo "$MONGODB_URI" | sed -E 's#(://[^:]+:)[^@]*@#\1***@#'2Fix
Create or edit the database user in Atlas, copy the cluster connection string again, and put the new password into your environment variable.
# .env
MONGODB_URI="mongodb+srv://appuser:NEW_PASSWORD@cluster0.example.mongodb.net/mydb"3Verify
Connect from the app or from mongosh with the same string.
mongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"Confirmed by mongodb.com
Cause 2 of 3
Special characters in the password are not percent-encoded
1Check
In a connection string URI, special characters in the username or password must be encoded. Do not encode the password when you paste it outside a URI, such as into mongosh prompts.
node -e "console.log(encodeURIComponent(process.argv[1]))" 'p@ssw0rd!'2Fix
Encode the username and password before building the URI.
const user = encodeURIComponent(process.env.DB_USER);
const pass = encodeURIComponent(process.env.DB_PASS);
const uri = `mongodb+srv://${user}:${pass}@${process.env.DB_HOST}/mydb`;
await mongoose.connect(uri);3Verify
Start the app and watch for the connected message.
node server.jsConfirmed by mongodb.com
Cause 3 of 3
The authSource database is wrong
1Check
The authSource parameter names the database that holds the user's credentials. Without it, the default is the database named in the URI path when there is one, and admin otherwise. A string ending in /mydb can therefore look for the user in mydb while the user lives in admin, or the other way round.
echo "$MONGODB_URI" | grep -o 'authSource=[^&]*'2Fix
Add authSource to the connection string, set to the database that holds the user (admin in this example).
mongodb+srv://user:pass@cluster0.example.mongodb.net/mydb?authSource=admin3Verify
Connect again with the updated string.
mongosh "$MONGODB_URI" --eval "db.runCommand({ ping: 1 })"Confirmed by mongodb.com
How do I stop it coming back?
- Keep the connection string in an environment variable and never in source code.
- Always build the URI with encodeURIComponent on the user and password.
- Use a separate database user per app, so rotating one password affects one service.
- Test a new string in mongosh before deploying it.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Databases
Node.js in Docker Compose cannot find mysql2/promise
The app works on the host but fails after docker compose up
mysql2/promise is a path inside the mysql2 package.
2 causes, each with a fixDatabases
Elasticsearch rejects requests with circuit_breaking_exception: Data too large
circuit_breaking_exception with a reason that contains Data too large
A circuit_breaking_exception with 'Data too large' means Elasticsearch refused work to protect a node's JVM heap.
3 causes, each with a fixDatabases
JupyterLab cannot determine its build status without Node.js
Could not determine jupyterlab build status without nodejs
JupyterLab itself runs without Node.js, but source extensions need Node.js to rebuild it.
3 causes, each with a fixDatabases
MongoDB says duplicate key, but the value is null
MongoServerError: E11000 duplicate key error
A unique index in MongoDB stores a missing field as null, and only one null entry is allowed.
3 causes, each with a fixDatabases
mongodb-memory-server will not start under Jest or in Docker
NoSystemBinaryFoundError
When mongodb-memory-server fails to start, the real reason is hidden behind a generic message.
4 causes, each with a fixDatabases
updateOne() runs without an error but the document does not change
{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }
updateOne() reports what it did in its result.
4 causes, each with a fix