Overview
Theconditional middleware enables conditional execution of other middleware based on request properties.
Use it when you need:
- Skip middleware for certain routes
- Apply middleware conditionally
- Dynamic middleware chains
Installation
Quick Start
Examples
Path-Based
Method-Based
Header-Based
Combine Conditions
API Reference
Functions
Technical Details
HTTP Conditional Request Processing
The conditional middleware implements HTTP conditional request handling as per RFC 7232. It provides efficient caching mechanisms through ETags and Last-Modified headers. Core Components:-
Response Capture: The middleware intercepts the response using a custom
responseCapturewriter that buffers both the status code and body content before sending it to the client. -
ETag Generation: By default, ETags are generated using MD5 hashing of the response body. The middleware supports both strong and weak ETags:
- Strong ETag:
"hash-value" - Weak ETag:
W/"hash-value"
- Strong ETag:
-
Last-Modified Handling: When a
ModTimeFuncis provided, the middleware sets the Last-Modified header and processes If-Modified-Since conditional requests.
- Check if request method is GET or HEAD (only these methods support conditional requests)
- Capture the response body and status code
- Generate ETag from response body (if enabled)
- Set Last-Modified header (if configured)
- Check If-None-Match header against ETag
- Check If-Modified-Since header against modification time
- Return 304 Not Modified if conditions match, or send full response
- The middleware buffers the entire response body for ETag generation
- MD5 hashing is used for ETag (not for security, just content fingerprinting)
- Only processes 2xx status codes to avoid caching errors
- Skips processing for non-GET/HEAD methods
Security Considerations
While MD5 is used for ETag generation, itβs important to note that this is not a security concern. ETags are content fingerprints for caching purposes, not cryptographic signatures. The MD5 algorithm is perfectly suitable for this use case.Best Practices
- Use clear condition names
- Keep conditions simple
- Document conditional behavior
- Test edge cases
- Consider response size when buffering for ETag generation
- Use weak ETags for frequently changing content
- Combine ETag and Last-Modified for optimal caching
- Provide custom ETagFunc for better performance with large responses