How long should a JWT secret be?
| Algorithm | Minimum key (RFC 7518) | Generated | base64url length |
|---|---|---|---|
| HS256 | 256 bits | 32 bytes | 43 characters |
| HS384 | 384 bits | 48 bytes | 64 characters |
| HS512 | 512 bits | 64 bytes | 86 characters |
A longer key than the minimum does not hurt, but it does not add security either: HMAC hashes keys longer than the block size first. Pick the size that matches the algorithm your library uses.
Using the secret in code
Node.js (jose)
import { SignJWT, jwtVerify } from "jose";
const key = new TextEncoder().encode(process.env.JWT_SECRET);
const token = await new SignJWT({ sub: "user_123" })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("15m")
.sign(key);
const { payload } = await jwtVerify(token, key, { algorithms: ["HS256"] });Java (jjwt)
// The value is base64url: use the URL decoder, not Decoders.BASE64
SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64URL.decode(System.getenv("JWT_SECRET")));Python (PyJWT)
import os, jwt
token = jwt.encode({"sub": "user_123"}, os.environ["JWT_SECRET"], algorithm="HS256")
payload = jwt.decode(token, os.environ["JWT_SECRET"], algorithms=["HS256"])HS256 vs RS256 vs ES256
| HS256 (HMAC) | RS256 (RSA) | ES256 (ECDSA) | |
|---|---|---|---|
| Key | one shared secret | private + public key | private + public key |
| Who can create tokens | everyone who can verify | only the private-key holder | only the private-key holder |
| Token signature size | 32 bytes | 256 bytes (2048-bit key) | 64 bytes |
| Best for | one service signs and verifies | many verifiers, JWKS endpoints | same as RS256, smaller tokens |
For a single backend, HS256 with a random 32-byte secret is simple and secure. Once a second team or service needs to verify tokens, move to asymmetric keys so a leak on the verifying side cannot be used to sign. Store the secret like any other: see .env best practices and GitHub Actions secrets.