🚀 Express.js Intermediate

How do you implement JWT authentication in Express.js?

Answer

JWT (JSON Web Token) authentication in Express involves two steps. Login: verify credentials, then sign a token: const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' }); send it in the response. Protected routes: create middleware that extracts the token from the Authorization: Bearer <token> header, verifies it: jwt.verify(token, process.env.JWT_SECRET), and attaches the decoded payload to req.user. If verification fails, respond with 401. Apply this middleware to protected routes: router.get('/profile', authMiddleware, profileHandler). Use the jsonwebtoken package. Store the JWT secret securely in environment variables, never hardcoded.