Closed
Description
Description
Currently, middleware can only modify requests before they are sent to the server. There's no way to short-circuit the middleware chain and return a response immediately, which is useful for cases like deduplicating or caching responses to avoid unnecessary network requests.
Proposal
Allow middleware's onRequest
hook to return a Response
object. When a middleware returns a Response:
- The request is not sent to the server
- Subsequent
onRequest
handlers are skipped onResponse
handlers are skipped
Example usage:
// Simple cache middleware example
const createCacheMiddleware = (): Middleware => {
const cache = new Map<string, Response>();
const getCacheKey = (request: Request) => `${request.method}:${request.url}`;
return {
async onRequest({ request }) {
const key = getCacheKey(request);
const cached = cache.get(key);
if (cached) {
// Return cached response, skipping actual request and remaining middleware chain
return cached.clone();
}
},
async onResponse({ request, response }) {
if (response.ok) {
const key = getCacheKey(request);
cache.set(key, response);
}
}
};
};
Checklist
- I’m willing to open a PR for this (see CONTRIBUTING.md)
Metadata
Metadata
Assignees
Type
Projects
Status
Done