What JWT_SECRET is
JWT_SECRET is the environment variable most projects use to hold the key that signs JSON Web Tokens with an HMAC algorithm such as HS256. Anyone who has it can create tokens your server will accept, so it must be random, long and never committed to source control.
1. Generate a strong value
For HS256 use at least 32 random bytes (256 bits). Use the JWT secret key generator, or create one locally:
openssl rand -hex 32
openssl rand -base64 32
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"Do not use words, project names or values such as secret or changeme.
2. Put it in a .env file
# .env
JWT_SECRET=paste-your-generated-value-here
JWT_EXPIRES_IN=15mAdd .env to .gitignore before your first commit, and commit a .env.example with placeholder values instead.
3. Load it in Node.js
import jwt from 'jsonwebtoken';
const secret = process.env.JWT_SECRET;
if (!secret) throw new Error('JWT_SECRET is not set');
const token = jwt.sign({ sub: userId }, secret, { algorithm: 'HS256', expiresIn: '15m' });
const payload = jwt.verify(token, secret, { algorithms: ['HS256'] });Use node --env-file=.env app.js on current Node.js versions, or the dotenv package. Fail on startup when the variable is missing rather than falling back to a default.
4. Separate secrets for access and refresh tokens
If you issue both access and refresh tokens, give each its own secret so a leak of one does not compromise the other:
JWT_ACCESS_SECRET=...
JWT_REFRESH_SECRET=...5. Docker and production
- Docker: pass it at runtime with
--env-fileor your orchestrator's secrets, not withENVin the Dockerfile, which bakes it into the image. - Hosting platforms: set it in the project's environment variable or secrets settings. Use a different value per environment.
- Cloud secret managers: AWS Secrets Manager, Google Secret Manager or HashiCorp Vault can inject the value at startup and make rotation easier.
6. If it leaks
Generate a new secret, deploy it, and accept that existing tokens signed with the old one become invalid and users must sign in again. Short token lifetimes limit the damage while you rotate.
Checklist
- At least 32 random bytes for HS256.
.envis in.gitignore.- The app refuses to start without the variable.
- Different secrets for each environment and for access vs refresh tokens.
- You pin the algorithm when verifying tokens.
Need another kind of secret? Try the secret key generator or the JWT token generator.