typescriptintermediate
Response Compression Middleware
Native zlib-based middleware that gzip-compresses responses above a size threshold.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { Request, Response, NextFunction } from 'express';
import { gzipSync } from 'zlib';
export function compress(thresholdBytes = 1024) {
return (req: Request, res: Response, next: NextFunction) => {
const originalJson = res.json.bind(res);
res.json = function (body: unknown) {
const raw = JSON.stringify(body);
const acceptsGzip = req.headers['accept-encoding']?.includes('gzip');
if (acceptsGzip && Buffer.byteLength(raw) > thresholdBytes) {
const compressed = gzipSync(raw);
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Content-Type', 'application/json');
return res.send(compressed);
}
return originalJson(body);
};
next();
};
}Use Cases
- Reducing API payload size
- Improving page load times
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Compression with zlib
Compress and decompress data using gzip, deflate, and brotli with Node.js built-in zlib module.
Best for: API response compression
#nodejs#zlib
typescriptintermediate
ETag Caching Middleware
Express middleware that generates ETags and handles 304 Not Modified responses for bandwidth savings.
Best for: API caching
#express#caching
typescriptintermediate
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
Best for: REST API authentication
#jwt#express
typescriptintermediate
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Best for: API abuse prevention
#express#rate-limit