Skip to content

Allow returning Response from onRequest callback #2072

Closed
@p-dubovitsky

Description

@p-dubovitsky

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

Metadata

Metadata

Assignees

Labels

enhancementNew feature or requestopenapi-fetchRelevant to the openapi-fetch library

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions