Overview
Thenocache middleware sets headers to prevent browsers and proxies from caching responses. Use it for sensitive data or frequently changing content.
Installation
Quick Start
Headers Set
Examples
Global No-Cache
Specific Routes
API Group
API Reference
When to Use
- User-specific data
- Authentication responses
- Frequently changing data
- Sensitive information
- Real-time data
Technical Details
The nocache middleware is implemented as a simple wrapper that sets anti-caching headers before passing control to the next handler in the chain.Implementation
The middleware:- Retrieves the response header object from the context
- Sets four HTTP headers to prevent caching at multiple levels:
Cache-Control: Provides comprehensive cache directives for HTTP/1.1Pragma: Backward compatibility with HTTP/1.0 cachesExpires: Sets expiration to prevent cachingSurrogate-Control: Controls CDN and proxy caching behavior
- Calls the next handler in the middleware chain
Performance
- Zero-allocation implementation
- Minimal overhead (4 header writes per request)
- No configuration or state management required
- Thread-safe for concurrent requests
Best Practices
- Apply to routes serving sensitive or user-specific data
- Use sparingly on static content to avoid performance degradation
- Consider combining with HTTPS for maximum security
- Test cache behavior with browser developer tools
- Apply at the route level rather than globally when possible
Testing
The middleware includes comprehensive tests to verify correct header configuration.Related Middlewares
- cache - Enable caching