How to implement JWT authentication in Node.js
· Category: Node.js
Short answer
Use the jsonwebtoken library to sign payloads with a secret or private key. Send the resulting JWT to the client, who includes it in the Authorization header. Verify the token on protected routes before processing requests.
Details
A JWT contains a header, payload, and signature. Keep payloads small and never store sensitive data inside them because the payload is only Base64Url-encoded, not encrypted. Use short-lived access tokens (minutes) and long-lived refresh tokens (days) stored securely in HttpOnly cookies. Rotate refresh tokens on every use to mitigate theft.
On the server, validate the signature and expiration before trusting claims. For Express, write middleware that returns 401 for missing or invalid tokens. To protect against brute-force login attempts, combine this with How to implement rate limiting in Express.js. For environment-specific secrets, see How to use environment variables in Node.js applications.
Tips
- Use asymmetric signing (RS256) if multiple services need to verify tokens but only one should issue them.
- Always validate the
algheader to prevent algorithm-switching attacks. - For understanding the difference between authentication and authorization, see authentication vs authorization.