Skip to content

Latest commit

 

History

History
49 lines (33 loc) · 2.38 KB

File metadata and controls

49 lines (33 loc) · 2.38 KB

Hybrid Proxy

Some of your API endpoints are real and running; others are not ready yet, have side effects you want to suppress, or are being replaced. You need to mock some paths and forward others to the real backend simultaneously.

Problem

You cannot route all traffic to the real backend — some paths don't exist yet, would cause side effects, or you want to test custom behavior there. But you also cannot mock everything when the real backend exists and you want real data on the stable paths.

Solution

Start Counterfact with --proxy-url pointing at the real backend. Every request is forwarded to the real backend by default. For the paths you want to control, add a route handler — Counterfact serves those from your code and forwards everything else. Toggle individual paths between mock and real at runtime using the REPL, without editing files or restarting the server.

Example

npx counterfact@latest openapi.yaml api --proxy-url https://api.example.com

Add a route handler for any path you want to mock:

// api/routes/payments.ts
export const POST: HTTP_POST = ($) => {
  return $.response[200].json({ transactionId: "mock-txn-001" });
};

Requests to /payments are now served by your handler; all other requests are forwarded to https://api.example.com.

Toggle individual paths at runtime from the REPL without touching any files:

⬣> .proxy on /payments    # forward /payments/* to the real API
⬣> .proxy off /payments   # mock /payments/* again
⬣> .proxy off             # mock everything

Consequences

  • The real backend must be reachable from your machine; the proxy adds a network hop.
  • Handler hot reload works on mocked paths; toggling proxy mode does not require a restart.
  • Forwarded requests carry the original headers and body; you do not have control over the real backend's response.
  • Using real paths alongside mocked paths makes it easier to detect divergence between the real API and the mock as the spec evolves.

Related Patterns