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.
jsonwebtoken – For generating and verifying JWTs
bcrypt – For hashing passwords (optional but recommended)
app.js example:
jwt.sign(payload, secret, options) generates a token
expiresIn sets token expiration
Create middleware to verify tokens:
Protected route example:
Client sends header: Authorization: Bearer
Middleware verifies token and allows access
JWTs are stateless and expire automatically
Use refresh tokens to generate new access tokens without re-login
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.
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.
Take quizzes related to this topic and see where you stand!
Start Quiz Now