Using JWT (JSON Web Tokens) with Express
⏱ Estimated reading time: 2 min
JWT (JSON Web Token) is a compact, URL-safe token format that allows you to securely transmit information between client and server.
It is widely used for stateless authentication in REST APIs.
1. Install Required Packages
-
jsonwebtoken– For generating and verifying JWTs -
bcrypt– For hashing passwords (optional but recommended)
2. Generate JWT on Login
app.js example:
-
jwt.sign(payload, secret, options)generates a token -
expiresInsets token expiration
3. Protect Routes with JWT
Create middleware to verify tokens:
Protected route example:
-
Client sends header:
Authorization: Bearer -
Middleware verifies token and allows access
4. Refresh Tokens (Optional)
-
JWTs are stateless and expire automatically
-
Use refresh tokens to generate new access tokens without re-login
5. Best Practices
-
Never store secrets in code – use environment variables (
process.env.SECRET_KEY). -
Use HTTPS to protect tokens in transit.
-
Set short expiration time for access tokens and long expiration for refresh tokens.
-
Do not store sensitive data in JWT payload.
-
Use middleware for central token validation.
6. Example Project Structure
-
auth.js→ Handles login and token issuance -
authMiddleware.js→ Protects routes with JWT
JWT is a powerful method for stateless authentication and works perfectly with REST APIs built using Express.js.
Register Now
Share this Post
← Back to Tutorials