typescriptintermediate

Response Compression Middleware

Native zlib-based middleware that gzip-compresses responses above a size threshold.

typescript
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.