Secret Generation·5 min read·Updated October 25, 2026

How to Generate a Secure JWT Secret in Node.js, Linux CLI, and Python

Generating a secure JWT secret is the foundational first step of building a token-based authentication service. This guide covers verified code snippets across multiple languages and runtimes using true CSPRNG sources.

Method 1: Node.js Crypto Module

In Node.js applications, use the native `crypto.randomBytes()` API. Never use `Math.random()` or third-party random number packages that lack cryptographic auditing.
javascriptGenerating a 256-bit JWT secret in Node.js
// 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)

OpenSSL is universally installed on modern Unix servers and provides an immediate, foolproof command for `.env` initialization:
bashOpenSSL command for production server deployment
# Generate a 512-bit (64 byte) secret for HS512:
openssl rand -base64 64 | tr -d '
'

Method 3: Python secrets Module

Python 3.6+ includes the `secrets` standard library, designed specifically for cryptographic keys and authentication tokens.
pythonCryptographically secure generation in Python 3
import secrets

# 256-bit (32 bytes) URL-safe token
jwt_secret = secrets.token_hex(32)
print(f"JWT_SECRET={jwt_secret}")
Generate in Browser

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.

Launch Generator

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).

How to Generate a Secure JWT Secret (Node.js, Bash, Python & Go) | JWT Secret Key Generator | JWT Secret Key Generator