Authentication Middleware with JWT
Build secure authentication into your Express app using JSON Web Tokens, and learn how to protect routes with custom auth middleware.
Authentication Middleware with JWT is a free Node.js Backend Development Bootcamp lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Node.js Backend Development Bootcamp learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Tokens?
HTTP is stateless: the server forgets you between requests. To know who is making a request, the client sends proof of identity each time.
JSON Web Tokens (JWT) are a popular, stateless way to carry that proof without storing sessions on the server.
Anatomy of a JWT
A JWT is three Base64 sections separated by dots:
- Header: the signing algorithm
- Payload: claims like user id and role
- Signature: verifies the token was not tampered with
The payload is encoded, not encrypted — never put secrets in it.
// xxxxx.yyyyy.zzzzz
// header.payload.signatureInstalling jsonwebtoken
The jsonwebtoken package handles creating and verifying tokens.
// npm install jsonwebtoken
const jwt = require('jsonwebtoken');Signing a Token on Login
After verifying a user's credentials, call jwt.sign() with the payload, a secret, and options like expiry. Send the resulting token back to the client.
const token = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
res.json({ token });Sending the Token
The client stores the token and sends it back on each request, usually in the Authorization header using the Bearer scheme.
// Authorization: Bearer eyJhbGci...Reading the Token in Middleware
Auth middleware extracts the token from the header. Split off the Bearer prefix to get the raw token string.
function auth(req, res, next) {
const header = req.get('Authorization') || '';
const token = header.split(' ')[1];
// verify next...
}Verifying the Token
jwt.verify() checks the signature and expiry. If valid it returns the decoded payload; if not it throws, so wrap it in try/catch.
try {
const payload = jwt.verify(token, process.env.JWT_SECRET);
req.user = payload;
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}Complete Auth Middleware
Putting it together, this middleware rejects missing or invalid tokens and attaches the user to the request for downstream handlers.
function auth(req, res, next) {
const token = (req.get('Authorization') || '').split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch {
res.status(401).json({ error: 'Invalid token' });
}
}Protecting Routes
Apply the middleware to any route that requires login. Express runs it before the handler, blocking unauthenticated requests automatically.
app.get('/profile', auth, (req, res) => {
res.json({ id: req.user.userId });
});Role-Based Authorization
Authentication answers "who are you?"; authorization answers "are you allowed?". A second middleware can check req.user.role set by the auth step.
function requireAdmin(req, res, next) {
if (req.user.role !== 'admin') {
return res.status(403).json({ error: 'Forbidden' });
}
next();
}
app.delete('/users/:id', auth, requireAdmin, handler);Security Best Practices
Keep tokens safe:
- Store the secret in an environment variable, never in code
- Use short expiry times and refresh tokens for longer sessions
- Always serve over HTTPS
- Return
401for missing/invalid auth,403for insufficient permissions
Quick Check
Test your understanding of JWT auth.
Recap
You built stateless authentication with JWT:
- Sign a token on login with
jwt.sign() - Send it via the
Authorization: Bearerheader - Verify it in custom middleware with
jwt.verify() - Attach
req.userand protect routes - Add role checks for authorization
This is the foundation of secure Express APIs.
Frequently asked questions
Is the “Authentication Middleware with JWT” lesson free?
Yes — the full text of “Authentication Middleware with JWT” is free to read here on the web, and the Node.js Backend Development Bootcamp course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Node.js Backend Development Bootcamp course, upgrade to CoddyKit PRO.
What will I learn in “Authentication Middleware with JWT”?
Build secure authentication into your Express app using JSON Web Tokens, and learn how to protect routes with custom auth middleware. You practise Node.js Backend Development Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Node.js Backend Development Bootcamp?
No prior experience is required. Node.js Backend Development Bootcamp on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Authentication Middleware with JWT” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Node.js Backend Development Bootcamp lesson?
Yes. Every Node.js Backend Development Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Developing Custom Express Middleware
- Global Error Handling Strategies
- Input Validation with Joi/Express-Validator
- Authentication Middleware with JWT