Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
Authentication with JWT
JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. It's widely used for stateless authentication in APIs.
1. How it works
- User logs in with credentials.
- Server verifies credentials and creates a signed token.
- Server sends the token back to the client.
- Client sends the token in the
Authorizationheader for future requests. - Server verifies the signature and grants access.
2. Signing a Token
const jwt = require('jsonwebtoken');
const token = jwt.sign(
{ id: user._id, role: 'admin' },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);3. Verifying a Token (Middleware)
You can create a middleware to protect specific routes.
const auth = (req, res, next) => {
const token = req.header('x-auth-token');
if (!token) return res.status(401).send('Access denied. No token provided.');
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (ex) {
res.status(400).send('Invalid token.');
}
};
// Usage
app.get('/api/profile', auth, (req, res) => {
res.send(req.user);
});Security Tip: Never store sensitive information like passwords in a JWT, as the payload can be easily decoded (though not modified without the secret).