Fixing ERROR: secretOrPrivateKey Must Have a Value

December, 7th 2023 2 min read

This error appears when working with JWT libraries such as jsonwebtoken, and the secret key required to sign or verify tokens is missing or undefined. The issue usually comes from misconfigured environment variables, missing config values, or incorrect authentication setup.

1. Missing or Undefined Environment Variable

Most JWT setups use an environment variable like JWT_SECRET. If it’s missing, undefined, or empty, Node.js cannot sign tokens.

Example Fix

js
import jwt from 'jsonwebtoken';

const payload = { userId: 123 };
const secretKey = process.env.JWT_SECRET;

if (!secretKey) {
  throw new Error('JWT_SECRET environment variable is not defined');
}

const token = jwt.sign(payload, secretKey);
console.log(token);

Make sure you have a .env file:

plaintext
JWT_SECRET=your-secret-key-here

And load it using dotenv:

js
import 'dotenv/config';

2. Misconfigured JWT Strategy (Passport.js, Nest.js, Express.js)

If you’re using Passport.js, Nest.js, or any framework relying on JWT strategy configuration, make sure the secretOrKey value is provided correctly.

Passport.js Example

js
import passport from 'passport';
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt';

const secretKey = process.env.JWT_SECRET;

const opts = {
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: secretKey,
};

passport.use(
  new JwtStrategy(opts, (jwt_payload, done) => {
    return done(null, jwt_payload);
  })
);

Make sure the secret matches the one used to sign tokens.

3. Using NestJS with @nestjs/jwt

NestJS requires the secret field to be explicitly set:

ts
JwtModule.register({
  secret: process.env.JWT_SECRET,
  signOptions: { expiresIn: '1h' },
});

If secret is undefined, NestJS will throw the same error during token signing.

If you’re using local development and forgot to set env variables:

js
const token = jwt.sign({ userId: 1 }, 'local-secret-key');

This works, but avoid using hardcoded secrets in production.

5. Bonus: Validate Secret Early

Add a small check during app startup:

js
if (!process.env.JWT_SECRET) {
  console.error('❌ Missing JWT_SECRET');
  process.exit(1);
}

This avoids debugging issues later.


Conclusion

The "secretOrPrivateKey must have a value" error happens when the JWT secret is missing, undefined, or incorrectly configured. To fix it:

  • Make sure JWT_SECRET is defined in your environment.
  • Confirm your authentication strategy (Passport.js, Nest.js, Express.js) has a valid secretOrKey.
  • Avoid setting your secret to undefined, null, or an empty string.
  • Validate secrets during application startup.

Once the secret is correctly set, JWT signing and verification should work without issues.