0Pricing
TypeScript Academy · Lesson

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

Type-safe Express middleware and error handlers prevent common bugs in request handling pipelines.

Middleware Signature

A middleware function takes req, res, next. Use the RequestHandler type from express.
import { RequestHandler } from 'express';
const authMiddleware: RequestHandler = (req, res, next) => {
  if (!req.headers.authorization) return res.status(401).json({});
  next();
};

NextFunction

Import NextFunction to type the third parameter explicitly.
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

Error handlers need four parameters. TypeScript enforces this via the ErrorRequestHandler type.
import { ErrorRequestHandler } from 'express';
const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
  res.status(err.status ?? 500).json({ message: err.message });
};

Custom Error Class

Define a typed error class with a status code.
class AppError extends Error {
  constructor(public message: string, public status: number = 500) {
    super(message);
  }
}

Async Middleware Wrapper

Wrap async middleware to forward errors to the Express error handler.
function asyncHandler(fn: RequestHandler): RequestHandler {
  return (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
}

Auth Middleware with User Attachment

Attach the authenticated user to the request after token verification.
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

Use Zod in middleware to parse and type-narrow request bodies.
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

Apply typed middleware to specific routes.
router.use('/admin', authenticate, authorize('admin'));
router.get('/admin/users', asyncHandler(listUsers));

Logging Middleware

Typed request logging middleware.
const requestLogger: RequestHandler = (req, _res, next) => {
  console.log(`${req.method} ${req.path}`);
  next();
};

Global Error Handler Registration

Register the error handler as the last middleware in the chain.
app.use(requestLogger);
app.use('/api', apiRouter);
app.use(errorHandler); // must be last

Quick Check

How many parameters does an Express error handler have?

Recap

Use RequestHandler, ErrorRequestHandler, and NextFunction types for Express middleware. Wrap async handlers to forward errors. Use Zod in middleware for typed request body validation.

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

  1. Setting Up TypeScript with Node.js
  2. Typing Express Request and Response
  3. Typed Middleware and Error Handlers
  4. Environment Variables and Config Typing
← Back to TypeScript Academy