Custom Middleware Types in Express
You'll learn how to properly type Express middleware functions with NextFunction and extend the Request object with custom properties for type-safe middleware chains.
The Core Problem
Express middleware functions have a specific signature: (req, res, next) => void. TypeScript needs to know what types these parameters have, especially when you add custom properties to req (like a user object after authentication).
Without proper typing, you lose autocomplete and safety when accessing those custom properties downstream.
Typing Basic Middleware
Express provides Request, Response, and NextFunction types from @types/express. A standard middleware function looks like this:
import { Request, Response, NextFunction } from 'express';
function loggingMiddleware(req: Request, res: Response, next: NextFunction): void {
console.log(`${req.method} ${req.path}`);
next();
}
The NextFunction type represents the callback that passes control to the next middleware. It's crucial for maintaining the chain.
Extending Request with Custom Properties
The real power comes when you need to attach data to req. For example, an auth middleware that adds req.user:
import { Request, Response, NextFunction } from 'express';
// Extend the Express Request interface
declare global {
namespace Express {
interface Request {
user?: {
id: string;
email: string;
};
}
}
}
function authMiddleware(req: Request, res: Response, next: NextFunction): void {
const token = req.headers.authorization;
if (token) {
// Simulate token verification
req.user = {
id: '123',
email: 'user@example.com'
};
next();
} else {
res.status(401).json({ error: 'Unauthorized' });
}
}
// Now TypeScript knows about req.user in route handlers
function profileHandler(req: Request, res: Response): void {
if (req.user) {
res.json({ user: req.user }); // ✓ Type-safe access
}
}
You use declaration merging with the global Express.Request interface to add your custom properties. This makes them available throughout your application.
Error-Handling Middleware Types
Error middleware has a different signature with four parameters:
import { Request, Response, NextFunction } from 'express';
function errorMiddleware(
err: Error,
req: Request,
res: Response,
next: NextFunction
): void {
console.error(err.message);
res.status(500).json({ error: 'Internal Server Error' });
}
Express distinguishes error middleware by the four-parameter signature. TypeScript enforces this through the parameter count.
Key Takeaway: Type Express middleware with Request, Response, and NextFunction from @types/express, and extend the global Express.Request interface using declaration merging to add custom properties that remain type-safe throughout your middleware chain.