Skip to content
Discussion options

You must be logged in to vote

You can implement JWT authentication in Express.js using the jsonwebtoken package.

Steps:

  1. Install the package:
    npm install jsonwebtoken

  2. Generate a token during login:
    const jwt = require('jsonwebtoken');

const token = jwt.sign({ userId: user._id }, 'secretKey', {
expiresIn: '1h'
});

  1. Verify the token using middleware:
    const verifyToken = (req, res, next) => {
    const token = req.headers['authorization'];

if (!token) return res.status(403).send('Token required');

jwt.verify(token, 'secretKey', (err, decoded) => {
if (err) return res.status(401).send('Invalid token');
req.user = decoded;
next();
});
};

  1. Use middleware in protected routes:
    app.get('/profile', verifyToken, (req, res) => {

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by Rahulab14
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants