Real-World Example: Augmenting Express
What you'll learn: How to add custom properties to Express's Request or Response interfaces using module augmentation patterns from real-world scenarios.
The Problem
When building Express applications, you often need to attach custom data to the request or response objects—like authenticated user information, session data, or request-specific context. TypeScript doesn't know about these custom properties by default, causing type errors when you try to access them.
The Solution: Module Augmentation
You can use module augmentation to extend Express's built-in interfaces, teaching TypeScript about your custom properties without modifying the Express library itself.
Common Pattern: Adding User to Request
The most typical scenario is attaching authenticated user data to req.user after middleware processes authentication:
// types/express.d.ts
import 'express';
declare module 'express' {
interface Request {
user?: {
id: string;
email: string;
role: 'admin' | 'user';
};
}
}
Now throughout your application, TypeScript knows about req.user:
import express from 'express';
const app = express();
app.get('/profile', (req, res) => {
if (req.user) {
// TypeScript knows user has id, email, role
res.json({ email: req.user.email });
} else {
res.status(401).send('Unauthorized');
}
});
Adding Multiple Custom Properties
You can augment with multiple properties at once:
declare module 'express' {
interface Request {
user?: { id: string; email: string };
requestId?: string;
startTime?: number;
}
interface Response {
sendSuccess?: (data: unknown) => void;
}
}
Why This Works
Module augmentation leverages declaration merging—the same feature that allows multiple interface declarations to combine. By declaring the express module again and redeclaring its Request interface, TypeScript merges your properties with the existing ones.
Key Takeaway: Use declare module 'express' with interface augmentation to type-safely extend Express request and response objects with custom properties, giving you autocomplete and type checking throughout your application.