Overview
Chain processing objects to handle requests
Middleware Pattern
7 implementations available
When to Use
- When you need to abstract data access logic
- When you want to make your code testable
- When you need to support multiple data sources
- When you want to decouple business logic from infrastructure
Available Implementations
Compression
Response compression middleware
npx hanma add compression
Gzip compressionBrotli supportThreshold configuration
Apollo GraphQL Server
Apollo Server 4 with Express integration
npx hanma add graphql-server
Apollo Server 4 setupExpress middleware integrationContext for authentication
JWT Authentication
JWT middleware with role-based access
npx hanma add jwt-auth
JWT verificationRole-based access controlToken extraction from header/cookie
Routes Logger
HTTP request logging middleware
npx hanma add routes-logger
Morgan integrationCustomizable formatSkip conditions
Error Handler
Global error handling middleware
npx hanma add error-middleware
Global error catchingEnvironment-aware responsesError logging
Cache Control
HTTP caching headers middleware
npx hanma add cache-control
Cache-Control headersETag supportConditional requests
Basic Example
// Middleware Pattern implementation example
// This shows the basic structure of middleware pattern in Express.js
// Define your interface
interface IRepository {
findAll(): Promise<T[]>;
findById(id: string): Promise<T | null>;
create(data: CreateDto): Promise<T>;
update(id: string, data: UpdateDto): Promise<T>;
delete(id: string): Promise<void>;
}
// Implement the pattern
class MiddlewareRepository implements IRepository {
async findAll(): Promise<T[]> {
// Implementation
}
async findById(id: string): Promise<T | null> {
// Implementation
}
async create(data: CreateDto): Promise<T> {
// Implementation
}
async update(id: string, data: UpdateDto): Promise<T> {
// Implementation
}
async delete(id: string): Promise<void> {
// Implementation
}
}
// Use the pattern
const repository = new MiddlewareRepository();
const items = await repository.findAll();
Frequently Asked Questions
What is Middleware Pattern?
Chain processing objects to handle requests. It's a well-established software design pattern that helps organize code for better maintainability and testability.
How does Middleware Pattern work with Express.js?
Express.js provides excellent support for this pattern through its dependency injection system and middleware composition.
What are the benefits?
Improved testability, separation of concerns, easier maintenance, and flexibility to change implementations without affecting business logic.
When should I avoid this pattern?
For very simple applications with minimal logic, the pattern may add unnecessary complexity. Use judgment based on project requirements.