Generate Secure JWT Secret Keys via Terminal on macOS
Generate cryptographically strong JWT secret keys on macOS using Node.js or OpenSSL.
Generating a JWT secret key for symmetric algorithms (e.g., HS256) requires a cryptographically secure random string. Node.js and OpenSSL are bundled or easily installed on macOS, enabling direct generation from Terminal.
1. Generate Hexadecimal Secret with Node.js
Install Node.js via Homebrew if missing:
1
brew install node
Generate a 32-byte (64 hex characters) secret:
1
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
Use the output as your JWT secret in environment files or application configs:
1
JWT_SECRET=your_generated_string_here
Reference: Node.js Crypto RandomBytes
2. Generate Base64 Secret with OpenSSL
Use built-in OpenSSL on macOS:
1
openssl rand -base64 32
For longer secrets (~80 chars):
1
openssl rand -base64 60
Set the output as your JWT secret:
1
JWT_SECRET=your_generated_string_here
Reference: OpenSSL RAND Manual
3. Generate Asymmetric Keys (RS256) with ssh-keygen
For RS256, generate a PEM-encoded RSA keypair:
1
2
ssh-keygen -t rsa -b 4096 -m PEM -f jwtRS256.key -N ""
openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub
Reference: Apple Security Keys
Recommendations
- Keep secrets private; never commit to version control.
- Use at least 32 bytes (256 bits) for symmetric secrets.
- Rotate keys if compromised.
- Use jsonwebtoken or similar libraries for signing.
☕ Support My Work
If you found this post helpful and want to support more content like this, you can buy me a coffee!
Your support helps me continue creating useful articles and tips for fellow developers. Thank you! 🙏