Generating a JWT secret in Node.js is one call to the built-in crypto module, but the details matter: the size must match the signing algorithm, the encoding decides how many characters you store, and the value must never reach your source tree. HS256 needs at least 32 random bytes, HS384 48 bytes and HS512 64 bytes, because RFC 7518 section 3.2 requires an HMAC key at least as large as the hash output. In Node.js that is crypto.randomBytes(32) and friends; the same bytes print as 64 hex characters or 43 unpadded Base64URL characters for HS256. This page gives you the one-line command, the jsonwebtoken sign and verify flow, and the .env setup that keeps the value out of git.

Generate a random JWT secret with crypto.randomBytes

Run this in any terminal with Node.js installed. It prints 32 random bytes from the operating system's CSPRNG, which is the minimum for HS256.

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"

Hex output is 64 characters and Base64URL output is 43 characters; both encode the same 32 bytes, so pick whichever your configuration format accepts. Standard Base64 works too, but the +, / and = characters need quoting in some .env parsers and shell scripts, which is why Base64URL is the safer default for a keyword like this. Use 48 bytes for HS384 and 64 for HS512.

Which Node.js version do I need?

crypto.randomBytes exists in every Node.js release that is still supported, so the generating line works on Node.js 18, 20, 22 and later. Two details have version floors: the base64url encoding used by toString('base64url') and Buffer.from(value, 'base64url') arrived in Node.js 14.18.0 and 15.7.0, and globalThis.crypto.getRandomValues became available in Node.js 19.0.0. If a runtime prints an error about an unknown encoding, it is older than 14.18; upgrade rather than substituting hex, because the var name should always describe the encoding its value actually uses.

Secret size by algorithm (RFC 7518 section 3.2)
AlgorithmMinimum keyHex charactersBase64URL characters
HS25632 bytes6443
HS38448 bytes9664
HS51264 bytes12886

randomBytes vs getRandomValues

crypto.randomBytes is the classic Node.js API and is available in every supported release. crypto.getRandomValues is the Web Crypto method that browsers expose and that Node.js 19 and later also exposes on globalThis.crypto, so a shared module can call it in both environments. Both draw from a CSPRNG; getRandomValues is limited to 65536 bytes per call, which is irrelevant for a 32 to 64 byte key. Never reach for Math.random, a timestamp or a UUID here: none of them is a secret generator.

// Works in Node.js 19+ and in browsers (crypto.getRandomValues)
const bytes = crypto.getRandomValues(new Uint8Array(32));
const secret = Buffer.from(bytes).toString('hex'); // 64 hex characters
console.log(secret);

Common Node.js JWT errors and fixes

These are the messages Node.js projects hit most often with jsonwebtoken 9. The names and texts below were reproduced on 2026-11-29 with Node.js 24.22.2 and jsonwebtoken 9.0.3; your stack trace will differ, but the cause is the same.

jsonwebtoken errors, causes and fixes
ErrorCauseFix
Error: secretOrPrivateKey must have a valuejwt.sign or jwt.verify received undefined or null, usually because .env was loaded after the call or the variable name differs.Load dotenv/config before the code that signs; check process.env.JWT_SECRET; keep the variable name identical in .env, .env.example and the deploy settings.
JsonWebTokenError: invalid signatureThe token was signed with different bytes: another environment's key, a rotated secret, or one side decoded a Base64URL value while the other used the raw string.Use one representation everywhere. With JWT_SECRET_B64URL, decode it once with Buffer.from(value, 'base64url') in every service, and print secret.length (32 for HS256) to confirm the bytes match.
TokenExpiredError: jwt expiredThe exp claim is in the past. This is normal for a stale token and is not a key problem.Issue a new token or refresh it; allow a few seconds of clockTolerance only if the servers' clocks genuinely drift.
JsonWebTokenError: jwt malformedThe value is not three Base64URL segments: a truncated copy, an empty variable, or quotes and whitespace included from .env.Trim the value, confirm it has two dots and check token.split('.').length === 3 before verifying.
JsonWebTokenError: invalid algorithmverify()'s algorithms list does not include the token's alg, for example an HS512 token checked with algorithms: ['HS256'].Pass the algorithm you signed with, and never let the token choose it for you.

Keep the signing key out of logs: print secret.length rather than the value when debugging, and never commit .env.

Store the secret in .env and keep it out of git

Put the value in a file that is never committed, list that file in .gitignore, and load it at the top of your entry point. .env.example is safe to commit because it contains only the variable name.

# .env
JWT_SECRET=<paste-the-64-hex-or-43-base64url-character-value-here>
# .gitignore
.env
.env.*
!.env.example
// .env.example (committed, no real values)
JWT_SECRET=
// app.cjs, put this before anything that reads process.env
require('dotenv').config();
const secret = process.env.JWT_SECRET;
if (!secret) throw new Error('JWT_SECRET is not set');

In production, do not ship the .env file. Set JWT_SECRET as an environment variable in your hosting platform, container secret or CI pipeline, and rotate it if it was ever printed, logged or committed.

Sign and verify a token with jsonwebtoken

Install the library and keep the algorithm explicit in both directions. Listing algorithms on verify blocks a token from switching to a weaker algorithm.

// npm install jsonwebtoken@9 dotenv
require('dotenv').config();
const jwt = require('jsonwebtoken');

const secret = process.env.JWT_SECRET;
if (!secret) throw new Error('JWT_SECRET is not set');

const token = jwt.sign({ sub: 'user-42', role: 'reader' }, secret, {
  algorithm: 'HS256',
  expiresIn: '15m',
});

const claims = jwt.verify(token, secret, { algorithms: ['HS256'] });
console.log(claims.sub); // user-42

Change the algorithm to HS384 or HS512 only after switching to a key of at least 48 or 64 bytes. The same secret must be used by every service that signs or verifies the token; if one service decodes the value to bytes first, every service has to decode it the same way.

Use a different secret per environment

Rotate the key on a schedule and immediately after a suspected leak. Access tokens normally live 5 to 15 minutes, so a rotation window of a day is enough to let old tokens expire when you use the kid approach described in the questions below.

Frequently asked questions

Should I hardcode the JWT secret in my Node.js code?

No. A literal in a source file ends up in git history, in pull request diffs, in logs and in any bundle you build, and removing it later does not undo the exposure. Read the secret from an environment variable with process.env, keep the .env file out of version control, and inject the value from a secret manager or your hosting provider in production. If a secret was ever committed, rotate it: assume it is compromised.

Is a 32-character JWT secret enough in Node.js?

Only if those 32 characters are 32 random bytes. A 32-character hex string is only 16 bytes, which is below the HS256 minimum in RFC 7518 section 3.2. The reliable recipe is crypto.randomBytes(32) for HS256, 48 for HS384 and 64 for HS512; converted with toString('hex') that gives 64, 96 and 128 characters, and with toString('base64url') 43, 64 and 86 characters. Random text of 43 letters and digits is also fine for HS256, but a phrase you typed is not.

How do I use different JWT secrets for development, staging and production?

Keep one code path that reads process.env.JWT_SECRET and let each deployment provide its own value. Locally that is a .env file loaded by dotenv; in CI and production it is an environment variable injected by your platform or secrets manager. Never reuse a production secret in development, and do not check real values into .env.example, which should contain only the variable names. Give staging and production different keys so a leaked test token cannot be trusted by production.

How do I rotate a JWT secret without logging users out?

Sign new tokens with the new key, but let the verifier accept both keys for a transition window longer than the longest token lifetime. The standard way is the kid header: put a key id in every token, keep a small map or JWKS endpoint from kid to key, and pick the key when verifying. In jsonwebtoken you read header.kid from jwt.decode(token, { complete: true }) and choose the matching entry. Remove the old key only after every token it signed has expired.

What is the difference between crypto.randomBytes and crypto.getRandomValues?

Both are cryptographically secure, and both are fine for JWT secrets. randomBytes is the Node.js callback and sync API and has no practical size limit, so it is the natural choice on the server. getRandomValues is the Web Crypto API that also exists in Node.js 19 and later as globalThis.crypto, so it is the way to write one snippet that runs in both Node and the browser; it is capped at 65536 bytes per call. Do not use Math.random, which is not a secure generator.

Do I need an online generator, or can I generate the secret in Node.js?

Node.js can do it alone: crypto.randomBytes(32) (48 bytes for HS384, 64 for HS512) reads from the operating system's CSPRNG, and one command prints a ready value. Both approaches produce the same kind of key, so pick by context: a terminal command when the secret must stay on the server, and a browser page when you want to compare lengths and encodings, produce a .env line or generate on a phone. What you should not do is ask a chatbot to invent a secret or paste a production secret into an unfamiliar site; check that a web generator makes the key locally, as this site does, and keep it out of URLs and logs.

How do I use a Base64URL secret from an online generator in Node.js?

Keep the value in one variable, JWT_SECRET_B64URL, and decode it before signing: Buffer.from(process.env.JWT_SECRET_B64URL, 'base64url') turns the 43-character HS256 value back into 32 bytes, and that Buffer is what jsonwebtoken should receive. Use the decoded Buffer on every service that verifies the same tokens; if one service decodes the value and another uses the 43-character string as-is, the two derive different keys and verification fails with "invalid signature". Print secret.length once to confirm 32, 48 or 64 bytes, then pass it to jwt.sign and jwt.verify with the matching algorithm.

Generate a JWT secret key