Method 1: Node.js Crypto Module
// Generate a 256-bit (32 bytes) hex string:
const crypto = require('crypto');
const secret = crypto.randomBytes(32).toString('hex');
console.log('JWT_SECRET=' + secret);Method 2: Linux & macOS CLI (OpenSSL)
# Generate a 512-bit (64 byte) secret for HS512:
openssl rand -base64 64 | tr -d '
'Method 3: Python secrets Module
import secrets
# 256-bit (32 bytes) URL-safe token
jwt_secret = secrets.token_hex(32)
print(f"JWT_SECRET={jwt_secret}")Need a cryptographically secure JWT secret right now?
Generate 128 to 512-bit keys in Hex or Base64 using Web Crypto with zero server transmission.
Frequently Asked Questions
Why should I never use Math.random() for secrets?
Math.random() is a pseudo-random number generator designed for speed, not security. Its internal state can be fully reverse-engineered from just a few observed outputs.
Should I hardcode the generated secret in my source files?
Never. Secrets must always be injected through environment variables (.env) or a secret manager (AWS Secrets Manager, HashiCorp Vault).
Related Technical Guides
Setting JWT_SECRET in Node.js: Production Security, dotenv, and Docker
How to configure JWT_SECRET in Node.js using dotenv, environment validation, Docker secrets, and secret managers. Complete code examples.
Secret GenerationJWT Secret Key Length Explained: Entropy, Bit Length, and RFC 7518 Standards
Why does JWT secret length matter? Learn RFC 7518 key size standards, entropy calculations, and why HS256 demands at least 256 bits (32 bytes) of randomness.