typescriptintermediate
ETag Caching Middleware
Express middleware that generates ETags and handles 304 Not Modified responses for bandwidth savings.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { Request, Response, NextFunction } from 'express';
import { createHash } from 'crypto';
export function etagMiddleware(req: Request, res: Response, next: NextFunction) {
const originalJson = res.json.bind(res);
res.json = function (body: unknown) {
const content = JSON.stringify(body);
const etag = `"${createHash('md5').update(content).digest('hex')}"`;
res.setHeader('ETag', etag);
if (req.headers['if-none-match'] === etag) {
return res.status(304).end();
}
return originalJson(body);
};
next();
}Use Cases
- API caching
- Reducing bandwidth costs
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
In-Memory Caching with LRU Strategy
Implement LRU cache with TTL expiration, size limits, and cache-aside pattern for Node.js applications.
Best for: API response caching
#nodejs#caching
typescriptintermediate
Response Compression Middleware
Native zlib-based middleware that gzip-compresses responses above a size threshold.
Best for: Reducing API payload size
#express#compression
typescriptadvanced
Caching Strategies in Next.js
Master Next.js caching with fetch cache, unstable_cache, revalidatePath, and revalidateTag patterns.
Best for: ISR page caching
#nextjs#caching
sqladvanced
Materialized View with Auto-Refresh
Create and maintain materialized views for expensive aggregate queries with concurrent refresh support.
Best for: Dashboard analytics
#materialized-view#performance