ETag class

Middleware that automatically generates and validates ETags.

This middleware intercepts responses and:

  1. Generates an ETag based on the response content
  2. Compares with the client's If-None-Match header
  3. Returns 304 Not Modified if they match
  4. Otherwise, adds the ETag header to the response

Note: This middleware buffers the response body to compute the ETag. For large responses, consider using the ETag context extension methods in your handlers instead.

Features:

  • Automatic ETag generation using MD5 hash
  • Support for weak ETags
  • If-None-Match header validation
  • 304 Not Modified responses for cached content
  • Custom ETag generator support

Example usage:

// Automatic ETag for all responses
app.use(ETag());

// Weak ETags
app.use(ETag(const ETagOptions.weak()));

// Custom generator
app.use(ETag(ETagOptions(
  generator: (content) => sha256.convert(content).toString(),
)));

// Manual ETag in handler
app.get('/data').handle((ctx) async {
  final data = await fetchData();
  final etag = '"${data.version}"';

  if (await ctx.checkEtag(etag)) {
    return; // 304 sent
  }

  await ctx.res.json(data);
});

HTTP Caching Flow:

  1. First request: Server returns response with ETag header
  2. Subsequent requests: Client sends If-None-Match with cached ETag
  3. If ETag matches: Server returns 304 Not Modified (no body)
  4. If ETag differs: Server returns new response with new ETag
Implemented types

Constructors

ETag([ETagOptions options = const ETagOptions()])
Creates an ETag middleware with the given options.
const

Properties

hashCode int
The hash code for this object.
no setterinherited
options ETagOptions
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

generateEtag(Uint8List content) String
Generates an ETag for the given content.
generateEtagFromString(String content) String
Generates an ETag for string content.
handle(Context ctx, NextFunction next) FutureOr<void>
override
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited