Handlers, Services, Middleware & Context
Learn how production backends structure requests using handlers, services, repositories, middleware, and request context to build clean, scalable, and maintainable systems.
Handlers, Services, Repository Pattern, Middleware, and Request Context
Three concepts that show up in every production backend: the handler/service/repository pattern, middleware, and request context. They solve different problems but work together to keep your code organized, testable, and secure.
This post walks through how a request flows through your server, where each layer fits, and how middleware and context tie everything together.
#Table of Contents
- Request Life Cycle Inside the Server
- Handlers, Services, and Repository Pattern
- Middleware
- Request Context
#Request Life Cycle Inside the Server
When a client sends an HTTP request, your server doesn't just "handle it." The request travels through stages before a response goes back.
The request enters your server, gets matched to a route, passes through optional middleware, reaches a handler, which coordinates services and repositories, and finally returns a response.
Step 1: Routing
After the operating system forwards the HTTP request to your server's port (3000, 4000, whatever you configured), routing takes over.
Your routing algorithm matches the request path and method to a registered route:
GET /users -> listUsersHandler
GET /users/:id -> getUserHandler
POST /users -> createUserHandler
Once matched, the request moves to the associated Handler - a function you predefined to handle that specific API endpoint.
#Handlers, Services, and Repository Pattern
You could write all your logic inside a single handler. Nothing stops you. But as your codebase grows, that approach becomes hard to test, hard to reuse, and hard to debug.
The handler/service/repository pattern separates concerns:
| Layer | Responsibility | Should Know About |
|---|---|---|
| Handler/Controller | HTTP concerns: parsing input, validation, status codes, response formatting | Request/response objects, routing |
| Service | Business logic: orchestration, external calls, data transformation | Service dependencies, domain rules |
| Repository | Data access: queries, inserts, updates, deletes | Database schema, query language |
This separation isn't dogma. It's a tool for scalability, maintainability, and easier debugging.
Controller/Handler Layer
Handlers are your HTTP boundary. In most frameworks, a handler receives two objects by default:
- The request object - contains headers, body, query params, path params
- The response object - used to set status, headers, and send data back
Your runtime provides these. In Go, they're function parameters. In Express, they're passed to your route callback. You don't create them.
First Responsibility: Extracting Data
Before any logic runs, pull the data you need from the request:
// GET /users?role=admin&limit=20
const role = req.query.role;
const limit = parseInt(req.query.limit, 10);
// POST /books
const { title, author, isbn } = req.body;
// GET /users/:id
const userId = req.params.id;The handler doesn't decide what to do with this data yet. It just extracts it based on the request method:
- GET: extract query params
- POST/PUT/PATCH: extract request body
- DELETE: may extract body or params
Second Responsibility: Deserialization (Binding)
HTTP payloads arrive as JSON strings. Your language needs native types to work with them.
// Go: bind JSON to struct
var input CreateBookInput
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}# Python: parse JSON to dict
import json
data = json.loads(request.body)This step is also called binding - converting the request body into your language's native format.
If deserialization fails, return 400 Bad Request immediately. Don't let malformed JSON reach your business logic.
Note: In Node.js/Express, middleware like
express.json()handles this upstream. In Go, Python, or Rust, you typically do it explicitly in the handler.
Third Responsibility: Validation and Transformation
Once data is in native format, validate it. Validate everything that comes from external clients:
- Path parameters
- Query parameters
- Request body
- Headers
// Example: validate book creation input
if (!input.title || input.title.length < 3) {
return res.status(400).json({ error: "Title is required (min 3 chars)" });
}
if (!isValidISBN(input.isbn)) {
return res.status(400).json({ error: "Invalid ISBN format" });
}After validation, optionally transform data for downstream convenience:
// Set default sort order if not provided
const sort = req.query.sort || 'created_at';
// Normalize email to lowercase
input.email = input.email.toLowerCase().trim();Transformations keep your service layer clean. Services shouldn't check "was this param provided?" - they should receive clean, predictable data.
Service Layer
Services contain your business logic. They should be framework-agnostic: no req, no res, no HTTP status codes.
// Go: service function signature
func CreateBook(ctx context.Context, repo BookRepository, input CreateBookInput) (*Book, error) {
// Business logic here
}# Python: service function
def create_book(repo: BookRepository, input: CreateBookInput) -> Book:
# Business logic here
passResponsibility of Service Layer
- Call one or more repository methods for database operations
- Orchestrate external API calls, email notifications, webhooks
- Apply domain rules: "users can't delete books they don't own"
- Return plain data or domain errors (not HTTP responses)
A service method might look like:
async function createBook(userId, bookData) {
// Check if user has permission
const user = await userRepo.findById(userId);
if (!user.canCreateBooks) {
throw new PermissionError("User cannot create books");
}
// Create the book
const book = await bookRepo.create({
...bookData,
createdBy: userId,
createdAt: new Date()
});
// Send notification
await emailService.sendWelcomeEmail(user.email, book.title);
return book;
}Notice: no HTTP logic. This function could be called from an API handler, a CLI tool, or a background job.
Repository Layer
Repositories handle data persistence. One repository method, one responsibility.
// Go: repository interface
type BookRepository interface {
Create(ctx context.Context, book *Book) error
FindByID(ctx context.Context, id string) (*Book, error)
List(ctx context.Context, filter BookFilter) ([]*Book, error)
}// JavaScript: repository class
class BookRepository {
async create(bookData) {
return await db.books.insert(bookData);
}
async findById(id) {
return await db.books.findOne({ _id: id });
}
async list({ sortBy, limit, offset }) {
return await db.books.find()
.sort(sortBy)
.limit(limit)
.skip(offset);
}
}Key Rules for Repositories
- Don't mix concerns:
findByIdreturns one book;listreturns many. Don't add an optionalidparam tolistto fetch a single record. - Don't include business logic: repositories fetch or persist data. They don't decide if a user can delete a book.
- Keep queries isolated: if you need to join three tables, that logic lives here, not in the service layer.
Orchestration Happens in Services
Services combine repository results:
async function getBookWithDetails(bookId) {
const [book, reviews, author] = await Promise.all([
bookRepo.findById(bookId),
reviewRepo.findByBookId(bookId),
userRepo.findById(book.authorId)
]);
return {
...book,
reviews: reviews.map(r => r.content),
authorName: author.name
};
}The service coordinates; repositories execute.
Returning to Controller Layer
After the service returns data, the handler formats the HTTP response:
// Handler: send success response
res.status(201).json(book);
// Handler: handle domain errors
if (err instanceof PermissionError) {
return res.status(403).json({ error: err.message });
}
// Handler: catch unexpected errors
if (err instanceof DatabaseError) {
logger.error("DB error", err);
return res.status(500).json({ error: "Internal server error" });
}The handler maps domain outcomes to HTTP status codes. Services throw domain errors; handlers translate them.
#Middleware
Middleware sits between the raw HTTP request and your handler. It's where you handle cross-cutting concerns: logging, auth, rate limiting, CORS.
Why "Middleware"
Because it runs in the middle of the request lifecycle:
Middleware functions execute in sequence. Each can:
- Read or modify the request
- Read or modify the response
- Short-circuit the pipeline by sending a response early
- Pass control to the next function via
next()
What Does a Middleware Receive
In most frameworks, middleware gets three arguments:
// Express-style middleware signature
function myMiddleware(req, res, next) {
// req: request object
// res: response object
// next: function to call the next middleware/handler
}The next Function
next is how middleware passes control forward:
function loggingMiddleware(req, res, next) {
console.log(`${req.method} ${req.path}`);
next(); // Continue to next middleware or handler
}If you don't call next(), the request hangs. If you send a response without calling next(), the pipeline stops - useful for auth failures or rate limit hits.
function authMiddleware(req, res, next) {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: "Missing token" });
// Don't call next() - request ends here
}
// Token valid: attach user to request and continue
req.user = verifyToken(token);
next();
}Why Use Middlewares
To avoid repeating code. Imagine you have 50 endpoints. Each needs:
- CORS headers
- Request logging
- Authentication checks
- Rate limiting
Without middleware, you'd copy-paste that logic into every handler. With middleware, you write it once and apply it globally or per-route.
Order of Middleware Matters
Middleware executes in the order you register it. Get the order wrong, and your app breaks.
// Wrong: auth runs before CORS
app.use(authMiddleware);
app.use(corsMiddleware); // Too late - browser already blocked the request
// Correct: CORS first, then auth
app.use(corsMiddleware);
app.use(authMiddleware);Common Middleware Examples
CORS Middleware
Adds headers to allow cross-origin requests from your frontend:
function corsMiddleware(req, res, next) {
const allowedOrigins = ['https://app.example.com'];
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
}
// Handle preflight OPTIONS request
if (req.method === 'OPTIONS') {
return res.sendStatus(204);
}
next();
}Security Headers Middleware
Sets headers that harden your app against common attacks:
function securityHeadersMiddleware(req, res, next) {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
next();
}Authentication Middleware
Verifies tokens and attaches user info to the request:
async function authMiddleware(req, res, next) {
try {
const token = extractToken(req.headers.authorization);
const payload = await verifyJWT(token);
// Attach to request context (see below)
req.context.userId = payload.sub;
req.context.role = payload.role;
next();
} catch (err) {
res.status(401).json({ error: "Invalid or expired token" });
}
}Rate Limiting Middleware
Prevents abuse by tracking request counts per IP or user:
function rateLimitMiddleware(windowMs, maxRequests) {
const store = new Map(); // In production, use Redis
return (req, res, next) => {
const key = req.ip;
const now = Date.now();
const windowStart = now - windowMs;
// Clean old entries
const requests = store.get(key)?.filter(t => t > windowStart) || [];
if (requests.length >= maxRequests) {
return res.status(429).json({ error: "Too many requests" });
}
requests.push(now);
store.set(key, requests);
next();
};
}
// Usage: max 100 requests per 60 seconds
app.use(rateLimitMiddleware(60_000, 100));Logging and Monitoring Middleware
Records request details for debugging and monitoring:
function loggingMiddleware(req, res, next) {
const start = Date.now();
// Log when response finishes
res.on('finish', () => {
const duration = Date.now() - start;
logger.info({
method: req.method,
path: req.path,
status: res.statusCode,
durationMs: duration,
ip: req.ip
});
});
next();
}Global Error Handling Middleware
Catches unhandled errors and formats consistent responses:
// Register this LAST - after all routes and middleware
function errorHandlerMiddleware(err, req, res, next) {
logger.error("Unhandled error", err);
if (err instanceof ValidationError) {
return res.status(400).json({ error: err.message, code: "VALIDATION_ERROR" });
}
if (err instanceof PermissionError) {
return res.status(403).json({ error: err.message, code: "PERMISSION_DENIED" });
}
// Default: internal server error
res.status(500).json({
error: "Internal server error",
code: process.env.NODE_ENV === 'production' ? undefined : err.stack
});
}Important: Error-handling middleware has four arguments
(err, req, res, next). Express distinguishes it from regular middleware by the argument count.
Place error handling middleware last. If an error occurs in your handler or any upstream middleware, the error handler needs to be downstream to catch it.
Compression Middleware
Reduces response size for large payloads:
// Using compression library
import compression from 'compression';
app.use(compression()); // Automatically compresses responses > 1KBData Parsing Middleware
Handles JSON, URL-encoded, or multipart bodies:
// Express built-in parsers
app.use(express.json()); // Parse JSON bodies
app.use(express.urlencoded({ extended: true })); // Parse form dataTypical Middleware Order
Register middleware in this general sequence:
- CORS - Block unauthorized origins early
- Security headers - Set protective headers on all responses
- Request parsing - Make body/query params available
- Logging - Record incoming requests
- Rate limiting - Throttle before expensive operations
- Authentication - Verify identity before business logic
- Your routes/handlers - Actual endpoint logic
- Error handling - Catch and format errors (must be last)
app.use(corsMiddleware);
app.use(securityHeadersMiddleware);
app.use(express.json());
app.use(loggingMiddleware);
app.use(rateLimitMiddleware(60_000, 100));
app.use(authMiddleware); // Optional: apply only to protected routes
// Public routes
app.get('/health', healthHandler);
// Protected routes
app.use('/api', authMiddleware);
app.post('/api/books', createBookHandler);
app.get('/api/books/:id', getBookHandler);
// Error handler - registered last
app.use(errorHandlerMiddleware);#Request Context
Middleware and handlers need a way to share data without tightly coupling functions. That's what request context provides.
What Is Request Context
Request context is a per-request storage bucket - a key-value store scoped to a single HTTP request. Data stored here is accessible to all middleware and handlers processing that request, but isolated from other concurrent requests.
Each request gets its own context. No data leaks between requests.
Why We Have Request Context
Without context, sharing data between middleware and handlers requires:
- Passing extra parameters through every function call
- Attaching properties directly to
req(works, but less explicit) - Using global state (dangerous in concurrent servers)
Context provides a clean, scoped alternative.
Example: Authentication Data in Context
Authentication middleware verifies a token and stores user info in context:
// Auth middleware
async function authMiddleware(req, res, next) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) return res.status(401).json({ error: "Missing token" });
try {
const payload = await verifyJWT(token);
// Store in request context
req.context = req.context || {};
req.context.userId = payload.sub;
req.context.role = payload.role;
req.context.permissions = payload.permissions;
next();
} catch (err) {
res.status(401).json({ error: "Invalid token" });
}
}Downstream handlers access this data without re-verifying the token:
// Handler: create a book
async function createBookHandler(req, res) {
const { title, author } = req.body;
// Get user info from context, not from client input
const userId = req.context.userId;
const role = req.context.role;
// Service layer uses userId for audit trail
const book = await bookService.create({ title, author, createdBy: userId });
res.status(201).json(book);
}Security note: Never trust client-provided user IDs. Always derive identity from authenticated context.
Example: Request ID for Tracing
Add a unique ID to each request for log correlation:
// Middleware: generate request ID
function requestIdMiddleware(req, res, next) {
const requestId = crypto.randomUUID();
// Store in context
req.context = req.context || {};
req.context.requestId = requestId;
// Also add to response headers for client debugging
res.setHeader('X-Request-ID', requestId);
next();
}Use the ID in logs and downstream service calls:
// Logging middleware
function loggingMiddleware(req, res, next) {
const start = Date.now();
res.on('finish', () => {
logger.info({
requestId: req.context.requestId,
method: req.method,
path: req.path,
status: res.statusCode,
durationMs: Date.now() - start
});
});
next();
}
// Service: call external API with request ID for tracing
async function callExternalService(data, context) {
return await fetch('https://api.external.com/endpoint', {
headers: {
'X-Request-ID': context.requestId,
'Authorization': `Bearer ${process.env.EXTERNAL_API_KEY}`
},
body: JSON.stringify(data)
});
}Now you can trace a single request across logs, services, and infrastructure.
Other Use Cases
Request context also handles:
Cancellation signals
// Go: context with timeout
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
// Pass ctx to downstream operations
book, err := repo.FindByID(ctx, id)Deadlines for external calls
// Node.js: abort fetch after 5 seconds
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch(url, { signal: controller.signal });
clearTimeout(timeout);
return await response.json();
} catch (err) {
if (err.name === 'AbortError') {
throw new Error("Request timed out");
}
throw err;
}Feature flags or tenant info
// Multi-tenant app: store tenant config in context
function tenantMiddleware(req, res, next) {
const subdomain = extractSubdomain(req.headers.host);
const tenant = tenantRepo.findBySubdomain(subdomain);
req.context = req.context || {};
req.context.tenant = tenant;
req.context.featureFlags = tenant?.featureFlags || {};
next();
}Context keeps request-scoped data accessible without global state or parameter sprawl.
Handlers, services, and repositories separate HTTP concerns from business logic from data access. Middleware handles cross-cutting concerns without duplicating code. Request context shares data across the pipeline without tight coupling.
These patterns aren't about following rules for rules' sake. They're about making your code:
- Easier to test (mock a repository, not an HTTP handler)
- Easier to change (swap databases without touching business logic)
- Easier to debug (trace a request with context IDs)
- Easier to scale (add middleware without rewriting handlers)
Start simple. Add layers as your app grows. And always validate at the edge - never trust input that crosses your server boundary.