Lesson 3 of 8
Typed Middleware & Error Handlers
Middleware is at the heart of Express. TypeScript types middleware through Declaration Merging on `Request` - custom middleware can add typed properties (`req.user`, `req.requestId`) visible to all downstream handlers. Typed error handlers catch typed errors and produce consistent JSON responses.
Middleware - Declaration Merging, Auth & Error Handling
// ── Extend Request with custom properties ────────────────────
// src/types/express.d.ts
declare global {
namespace Express {
interface Request {
user?: { id: number; email: string; role: "member" | "admin" };
requestId?: string;
startTime?: number;
}
}
}
export {};
// ── Auth middleware - adds req.user ───────────────────────────
import jwt from "jsonwebtoken";
import { Request, Response, NextFunction } from "express";
interface JwtPayload { userId: number; email: string; role: "member" | "admin"; }
function authMiddleware(req: Request, res: Response, next: NextFunction): void {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith("Bearer ")) {
res.status(401).json({ error: "Missing or invalid Authorization header" });
return;
}
try {
const token = authHeader.slice(7);
const payload = jwt.verify(token, process.env.JWT_SECRET) as JwtPayload;
req.user = { id: payload.userId, email: payload.email, role: payload.role };
next();
} catch {
res.status(401).json({ error: "Invalid or expired token" });
}
}
// ── Request ID middleware ─────────────────────────────────────
import { randomUUID } from "node:crypto";
function requestIdMiddleware(req: Request, _res: Response, next: NextFunction): void {
req.requestId = randomUUID();
req.startTime = Date.now();
next();
}
// ── Typed error class ─────────────────────────────────────────
class AppError extends Error {
constructor(
public readonly statusCode: number,
message: string,
public readonly code?: string,
) {
super(message);
this.name = "AppError";
}
}
// ── Error handler middleware - 4 args = error handler in Express ──
function errorHandler(
error: unknown,
req: Request,
res: Response,
_next: NextFunction, // must be declared even if unused
): void {
const requestId = req.requestId ?? "unknown";
if (error instanceof AppError) {
res.status(error.statusCode).json({
error: error.message,
code: error.code,
requestId,
});
return;
}
if (error instanceof Error) {
console.error(`[${requestId}]`, error);
res.status(500).json({ error: "Internal server error", requestId });
return;
}
res.status(500).json({ error: "Unknown error", requestId });
}
// Registered LAST in Express:
app.use(errorHandler);
// ── Using middleware in routes ─────────────────────────────────
router.delete(
"/tasks/:id",
authMiddleware, // adds req.user
async (req: Request<{ id: string }>, res: Response, next: NextFunction) => {
if (!req.user) { next(new AppError(401, "Unauthorized")); return; }
if (req.user.role !== "admin") { next(new AppError(403, "Forbidden")); return; }
const id = parseInt(req.params.id, 10);
await taskService.delete(id);
res.status(204).send();
},
);Common Mistakes
- Using `req.user` without Declaration Merging - accessing `req.user` without augmenting `Express.Request` gives a TypeScript error. The declaration merging in `express.d.ts` is the correct pattern.
- Not providing all 4 arguments to error handler - Express only recognises error-handling middleware when the function declares exactly 4 parameters `(err, req, res, next)`. With 3 parameters, Express treats it as regular middleware and errors pass through.
- Catching all errors and swallowing stack traces - log unknown errors with their stack trace in development. Only hide details in production (use `NODE_ENV` check).
Tip
Tip
Practice Typed Middleware Error Handlers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Typed Middleware & Error Handlers
Practice Task
Note
Practice Task - (1) Write a working example of Typed Middleware Error Handlers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Typed Middleware Error Handlers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Middleware is at the heart of Express.
- Using `req.user` without Declaration Merging - accessing `req.user` without augmenting `Express.Request` gives a TypeScript error. The declaration merging in `express.d.ts` is the correct pattern.
- Not providing all 4 arguments to error handler - Express only recognises error-handling middleware when the function declares exactly 4 parameters `(err, req, res, next)`. With 3 parameters, Express treats it as regular middleware and errors pass through.
- Catching all errors and swallowing stack traces - log unknown errors with their stack trace in development. Only hide details in production (use `NODE_ENV` check).
Finished this lesson?