Generate a Random String for a JWT Secret
Tala Amm

Tala Amm @talaamm

About: Computer Engineer • Full-Stack Dev • Rust, Go, JS Developer

Location:
Jerusalem
Joined:
Jul 5, 2025

Generate a Random String for a JWT Secret

Publish Date: Jul 31
6 0

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
Enter fullscreen mode Exit fullscreen mode

Node.js (JavaScript)

// Generate a 64-character random string
const crypto = require('crypto');
console.log(crypto.randomBytes(64).toString('hex'));
Enter fullscreen mode Exit fullscreen mode

Python

import secrets
print(secrets.token_hex(64))
Enter fullscreen mode Exit fullscreen mode

🛡️ Where Do You Store It?

In a .env file:

JWT_SECRET=9f7a41a6e23... (your generated key)
Enter fullscreen mode Exit fullscreen mode

And in your code (JavaScript):

const jwtSecret = process.env.JWT_SECRET;
Enter fullscreen mode Exit fullscreen mode

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.

Comments 0 total

    Add comment