Skip to content
ecdsa.com
jsonwebtoken (Node.js)JWT libraries

Error message

secret or public key must be provided

Also printed as

  • secretOrPrivateKey must have a value

`jwt.sign()` reports the same problem as "secretOrPrivateKey must have a value" (a plain `Error`).

jsonwebtoken (Node.js) — JsonWebTokenError from jwt.verify(); the sign() twin is a plain Error

What it means

`jwt.verify()` received a signed token but the key argument is empty (`undefined`, `null` or `""`). jsonwebtoken cannot check a signature without a key, so it stops before looking at the token. The signing side has a twin, `secretOrPrivateKey must have a value`, thrown by `jwt.sign()` for the same reason.

Why it happens

How to fix it

  1. 1.

    Validate configuration at startup

    Read required keys once when the process starts and exit with a clear message if one is missing. A misconfigured instance then never starts serving requests.

    js
    function requireEnv(name) {
      const value = process.env[name];
      if (!value) throw new Error(name + " is not set");
      return value;
    }
    
    const JWT_PUBLIC_KEY = requireEnv("JWT_PUBLIC_KEY"); // evaluated once at startup
  2. 2.

    Load environment files before anything else

    Import `dotenv/config` as the very first import, or use Node's built-in `--env-file` flag, so every module sees the values.

    js
    // Load .env before any module that reads process.env at import time.
    import "dotenv/config";
    import { app } from "./app.js";
    
    // Node 20.6+: no package needed
    // node --env-file=.env server.js

Related errors

Browse the full signature error database