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.
Previous
What is Nodemon and why is it useful with Express?
Next
What is Express middleware chaining and how does it work?
More Express.js Questions
View all →- Intermediate What is Express middleware chaining and how does it work?
- Intermediate What is the helmet package and why should you use it?
- Intermediate How do you implement rate limiting in Express.js?
- Intermediate What is input validation and how do you do it in Express?
- Intermediate How do you connect Express.js to MongoDB using Mongoose?