bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: undefined, stringShort answer
bcryptjs checks the types of its two arguments and, when either is wrong, throws Illegal arguments followed by the typeof of the first and the second. So undefined, string means the password is undefined. Read the pair: it tells you whether the password, the salt or the stored hash is the missing value.
Fix it fast
1Find out which cause you have
Print the typeof of both values right before the bcrypt call. The error message is built from exactly these two typeof results, in the same order.
console.log(typeof password, typeof saltOrHash); // hash(password, salt) -> first = password, second = salt or rounds // compare(password, hash) -> first = password, second = stored hash2Match what you see, then jump to its fix
- 1
Illegal arguments: undefined, string (or undefined, number) in a register or login routereq.body is empty because no body-parsing middleware ranFix - 2
Illegal arguments: string, undefinedThe stored hash is undefined when you call compare()Fix - 3
Illegal arguments: number, string, or object, stringThe password or salt is not a string or number of the right typeFix
- 1
What does the error look like?
Error: Illegal arguments: undefined, stringError: Illegal arguments: string, undefinedError: Illegal arguments: undefined, number
Cause 1 of 3
req.body is empty because no body-parsing middleware ran
1Check
In Express, req.body is undefined by default and is filled only when body-parsing middleware such as express.json() or express.urlencoded() runs before the route. Without it, req.body.password is undefined, or reading it throws first.
console.log(req.body);
console.log(req.headers['content-type']);2Fix
Register the parsers before your routes. Use express.json() for JSON bodies and express.urlencoded() for HTML form posts.
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// routes come after this3Verify
Post a body again and confirm the log now shows the password field as a string.
curl -X POST http://localhost:3000/register -H 'Content-Type: application/json' -d '{"email":"a@example.com","password":"secret123"}'Confirmed by expressjs.com
Cause 2 of 3
The stored hash is undefined when you call compare()
1Check
compare(password, hash) needs both as strings. The second one comes from your database row. It is undefined when no user was found, when the column name in code differs from the real one, or when the query excluded that field.
const user = await User.findOne({ email });
console.log(user && Object.keys(user.toObject ? user.toObject() : user));2Fix
Stop early when there is no user, and use the field name your schema really has. Also make sure the query returns the hash column.
const user = await User.findOne({ email }).select('+passwordHash');
if (!user || typeof user.passwordHash !== 'string') {
return res.status(401).json({ error: 'Invalid credentials' });
}
const ok = await bcrypt.compare(password, user.passwordHash);3Verify
Log in with a real account and with an unknown email; the first returns a result of true or false, the second a 401, and neither throws.
curl -X POST http://localhost:3000/login -H 'Content-Type: application/json' -d '{"email":"nobody@example.com","password":"x"}'Confirmed by raw.githubusercontent.com
Cause 3 of 3
The password or salt is not a string or number of the right type
1Check
In bcryptjs, hash() accepts a string password with a string salt or a number of rounds, and compare() needs two strings. A numeric PIN read from JSON, or an object from a nested form field, fails that check.
console.log(typeof req.body.password, req.body.password);2Fix
Reject non-string passwords at the edge, or convert an intentionally numeric value with String() before hashing. Always use the same conversion when you compare.
const { password } = req.body ?? {};
if (typeof password !== 'string' || password.length === 0) {
return res.status(400).json({ error: 'password is required' });
}
const hash = await bcrypt.hash(password, 10);3Verify
Send a number and an object as password; both get a 400 and no stack trace.
curl -X POST http://localhost:3000/register -H 'Content-Type: application/json' -d '{"password":12345}'Confirmed by github.com
How do I stop it coming back?
- Validate the request body (types and presence) before any call into bcrypt.
- Wrap login in one function that returns early when the user or the hash is missing.
- Keep the column name for the hash in one place, such as the model, and do not copy it as a string around the code.
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
Back end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
bcrypt.hash throws 'data and salt arguments required'
Error: data and hash arguments required
The bcrypt package throws this when hash gets null or undefined for the password or for the salt.
4 causes, each with a fixBack end
Express warns 'body-parser deprecated undefined extended'
body-parser deprecated undefined extended
The warning appears because urlencoded() was called without the extended option, which body-parser 1.x has warned about since version 1.4.0.
3 causes, each with a fixBack end
Browser blocks a stylesheet or script: MIME type mismatch with nosniff
The Network tab shows the asset URL answered with Content-Type text/html
With X-Content-Type-Options: nosniff the browser accepts a stylesheet only as text/css and a script only as a JavaScript type.
3 causes, each with a fixBack end
Discord OAuth2 login fails on the redirect_uri in an Express app
invalid_request
Discord compares the redirect_uri you send with the URL you registered for the application, and the token step must repeat the same value as the authorization step.
4 causes, each with a fix