typescriptintermediate

ETag Caching Middleware

Express middleware that generates ETags and handles 304 Not Modified responses for bandwidth savings.

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