jsonwebtoken throws: secretOrPrivateKey must have a value
Error: secretOrPrivateKey must have a valueShort answer
jwt.sign() throws this when the second argument is empty. In nearly every case it is undefined, because the environment variable holding the secret was never loaded. Check the value just before the call, load your .env file with Node's --env-file flag, and fix the variable name.
Fix it fast
1Find out which cause you have
Log whether the secret exists, without printing it, right before jwt.sign.
console.log('JWT secret set:', Boolean(process.env.JWT_SECRET));2Match what you see, then jump to its fix
- 1
The log line prints false, but the key is in your .env file.The .env file is never loadedFix - 2
The file defines JWT_KEY or JWTSECRET, the code reads JWT_SECRET.The variable name differs between code and .envFix - 3
It works locally and fails under PM2, Docker or systemd.The key is read from a file that is missing, or a variable that the process manager does not passFix
- 1
What does the error look like?
Error: secretOrPrivateKey must have a value
Cause 1 of 3
The .env file is never loaded
1Check
Node.js does not read .env by itself. Without a loader, process.env.JWT_SECRET is undefined.
node -e "console.log(Boolean(process.env.JWT_SECRET))"2Fix
Start the app with the built-in loader (Node.js 20.6 and later).
node --env-file=.env server.js
# package.json
"start": "node --env-file=.env server.js"3Verify
The log line now prints true.
node --env-file=.env -e "console.log(Boolean(process.env.JWT_SECRET))"Confirmed by nodejs.org
Cause 2 of 3
The variable name differs between code and .env
1Check
Names are case sensitive. Compare the key in the file with the one in the code.
grep -n "JWT" .env
grep -rn "process.env" src | grep -i jwt2Fix
Use one name in both places. Do not quote the value or add spaces around =.
JWT_SECRET=use-a-long-random-string3Verify
Restart the app and call the login route.
curl -i -X POST http://127.0.0.1:3000/login -H 'Content-Type: application/json' -d '{}'Confirmed by github.com
Cause 3 of 3
The key is read from a file that is missing, or a variable that the process manager does not pass
1Check
The library accepts a string, buffer, object or KeyObject. An empty value from a failed readFileSync or an unset variable reaches it as undefined or ''. Check what the running process sees.
pm2 env 0 | grep JWT_SECRET2Fix
Set the variable in the process manager's own config (PM2 ecosystem file, Docker env or systemd Environment), or pass the key as a buffer you have checked.
const secret = process.env.JWT_SECRET;
if (!secret) throw new Error('JWT_SECRET is missing at startup');
const token = jwt.sign({ sub: user.id }, secret, { expiresIn: '1h' });3Verify
The app now stops at startup if the secret is missing, instead of failing on the first login.
pm2 restart my-app --update-env && pm2 logs my-app --lines 20 --nostreamConfirmed by github.com
How do I stop it coming back?
- Check required environment variables once at startup and exit with a clear message.
- Keep the secret out of git; give each environment its own.
- Never pass a fallback like process.env.JWT_SECRET || '' to jwt.sign.
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
Security
jsonwebtoken rejects a token: invalid signature, jwt expired or jwt malformed
JsonWebTokenError: invalid signature
Each message points at a different step.
5 causes, each with a fixBack 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
bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: string, undefined
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.
3 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 fix