Typed Middleware and Error Handlers
Write type-safe Express middleware functions.
Typed Middleware and Error Handlers is a free TypeScript Academy lesson on CoddyKit — lesson 3 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 TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Welcome
Middleware Signature
import { RequestHandler } from 'express';
const authMiddleware: RequestHandler = (req, res, next) => {
if (!req.headers.authorization) return res.status(401).json({});
next();
};NextFunction
import { Request, Response, NextFunction } from 'express';
function logger(req: Request, res: Response, next: NextFunction): void {
console.log(req.method, req.path);
next();
}Error Handler Signature
import { ErrorRequestHandler } from 'express';
const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
res.status(err.status ?? 500).json({ message: err.message });
};Custom Error Class
class AppError extends Error {
constructor(public message: string, public status: number = 500) {
super(message);
}
}Async Middleware Wrapper
function asyncHandler(fn: RequestHandler): RequestHandler {
return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
}Auth Middleware with User Attachment
const authenticate: RequestHandler = async (req, res, next) => {
const user = await verifyToken(req.headers.authorization);
req.user = user; // requires module augmentation
next();
};Validation Middleware with Zod
function validate<T>(schema: ZodSchema<T>): RequestHandler {
return (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) return res.status(400).json(result.error);
req.body = result.data;
next();
};
}Router-Level Middleware
router.use('/admin', authenticate, authorize('admin'));
router.get('/admin/users', asyncHandler(listUsers));Logging Middleware
const requestLogger: RequestHandler = (req, _res, next) => {
console.log(`${req.method} ${req.path}`);
next();
};Global Error Handler Registration
app.use(requestLogger);
app.use('/api', apiRouter);
app.use(errorHandler); // must be lastQuick Check
Recap
Frequently asked questions
Is the “Typed Middleware and Error Handlers” lesson free?
Yes — the full text of “Typed Middleware and Error Handlers” is free to read here on the web, and the TypeScript Academy 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 TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Typed Middleware and Error Handlers”?
Write type-safe Express middleware functions. You practise TypeScript Academy 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 TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Typed Middleware and Error Handlers” 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 TypeScript Academy lesson?
Yes. Every TypeScript Academy 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
- Setting Up TypeScript with Node.js
- Typing Express Request and Response
- Typed Middleware and Error Handlers
- Environment Variables and Config Typing