Build HTTP APIs with routing, middleware, validation, controllers, and error handling.
Lessons
Issue and verify JSON Web Tokens for stateless auth.
JWT Authentication is easiest to learn by reading the example, changing it, and observing the result.
// npm install jsonwebtoken
import express from 'express';
import jwt from 'jsonwebtoken';
const app = express();
function auth(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ message: 'Invalid token' });
}
}
app.get('/api/profile', auth, (req, res) => res.json({ user: req.user }));
app.listen(3000);Practice the JWT Authentication example in a small scratch file, then explain what changed and why.