Skip to content

Fetch.functions.makeMiddlewareLayer

fx-fetch


fx-fetch / Fetch / makeMiddlewareLayer

makeMiddlewareLayer<R1, R2>(options): Layer<Fetch, never, R1 | R2>

Defined in: packages/fx-fetch/src/Fetch/makeMiddlewareLayer.ts:73

Creates a middleware Layer that allows customizing request and response handling.

The middleware can transform requests before they are sent and responses after they are received. Both mapRequest and mapResponse are optional - if not provided, they pass through unchanged.

R1 = never

R2 = never

MiddlewareOptions<R1, R2>

Layer<Fetch, never, R1 | R2>

import { Effect } from 'effect';
import { Fetch, Request } from 'fx-fetch';
// Middleware that adds authorization header to all requests
const authMiddlewareLayer = Fetch.makeMiddlewareLayer({
mapRequest: (request) =>
Effect.succeed(
Request.appendHeaders(request, { Authorization: 'Bearer token' })
),
});
Effect.gen(function* () {
const request = Request.unsafeMake({ url: 'https://api.example.com/data' });
const response = yield* Fetch.fetch(request);
}).pipe(
Effect.provide(authMiddlewareLayer), // ◀︎── Provide middleware layer
Effect.runPromise
);
import { Context, Effect, Layer } from 'effect';
import { Fetch, Request } from 'fx-fetch';
// Service for configuration
class Config extends Context.Tag('Config')<Config, { apiKey: string }>() {}
// Middleware with requirements - the Layer properly tracks Config requirement
const authMiddlewareLayer = Fetch.makeMiddlewareLayer({
mapRequest: (request) =>
Effect.gen(function* () {
const config = yield* Config;
return Request.appendHeaders(request, { 'X-API-Key': config.apiKey });
}),
});
// Type: Layer<Fetch, never, Config>
Effect.gen(function* () {
const request = Request.unsafeMake({ url: 'https://api.example.com/data' });
const response = yield* Fetch.fetch(request);
}).pipe(
Effect.provide(authMiddlewareLayer),
Effect.provide(Layer.succeed(Config, { apiKey: 'secret' })),
Effect.runPromise
);

1.2.0