How to Generate a Random String for a JWT Secret (Safely!)
When working with JWT (JSON Web Tokens) in your authentication system, one of the most important things is your JWT secret key. This is the string used to sign and verify the token, like a password for your server to trust the token.
So, how do you generate a good, secure one?
🧠 What Makes a Good JWT Secret?
- Long (at least 32+ characters)
- Random (not guessable, not a real word)
- Includes letters, numbers, and symbols
- Stored securely (like in
.env
files)
🔧 Generate One Using Code
Bash terminal (Most Recommended)
openssl rand -hex 64
Node.js (JavaScript)
// Generate a 64-character random string
const crypto = require('crypto');
console.log(crypto.randomBytes(64).toString('hex'));
Python
import secrets
print(secrets.token_hex(64))
🛡️ Where Do You Store It?
In a .env
file:
JWT_SECRET=9f7a41a6e23... (your generated key)
And in your code (JavaScript):
const jwtSecret = process.env.JWT_SECRET;
What NOT to Do ❌
- Don't hard-code your secret in the codebase
- Don't commit
.env
files to GitHub
✅ Final Tip
Regenerate your secret if you suspect a leak. Any old tokens will become invalid; which is exactly what you want in that case.