Write a plugin
Build a first plugin step by step, then look up the hooks and how a plugin reads the route.
When the built-in plugins don't cover what you need, such as a header your API asks for on every request, write your own. The built-in plugins are written with the same API. In this tutorial, you write a plugin that pins the API version on every request and check that it works. After that, the page describes every hook a plugin can use, and how a plugin reads which route a call is for.
Write your first plugin
The plugin you build sends an api-version header with every request, with
a default version that one call can change. It takes four steps.
Step 1: Define the plugin
A plugin is a name and one or more hooks. Create it with Fetch.plugin:
import * as from "effect/Effect";
import * as from "effect/http/HttpClientRequest";
import { } from "@monarcode/effetch";
export const = .({
: "apiVersion",
: { : "2024-06-01" },
: (, ) =>
.(
.(, "api-version", ..),
),
});The onRequest hook runs before each request is sent, and returns the
request to send. ctx.options holds the plugin's defaults, merged with
the call's changes, if it made any. A plugin needs defaults to take
options at all.
Fetch.plugin infers the plugin's name, options, errors and services from
what you give it. Calls can then change apiVersion by name, and TypeScript
checks their options.
Step 2: Add it to a client
List the plugin in the client's plugins option, as you would a built-in
one:
import * as from "effect/Effect";
import * as from "effect/http/HttpClientRequest";
import { } from "@monarcode/effetch";
const = .({
: "apiVersion",
: { : "2024-06-01" },
: (, ) =>
.(
.(, "api-version", ..),
),
});
export class extends .<>()("Api", {
: "https://api.example.com",
: [],
}) {}Every call the client makes sends api-version: 2024-06-01.
Step 3: Change it for one call
A call changes the plugin's options in its plugins option, under the
plugin's name:
import * as from "effect/Effect";
import * as from "effect/http/HttpClientRequest";
import { } from "@monarcode/effetch";
const = .({
: "apiVersion",
: { : "2024-06-01" },
: (, ) =>
.(
.(, "api-version", ..),
),
});
class extends .<>()("Api", {
: "https://api.example.com",
: [],
}) {}
export const = .(function* () {
const = yield* ;
yield* .("/reports", {
: { : { : "2025-01-01" } },
});
});Step 4: Check that it sends the header
To check the header without a server, run two calls against the fake
backend from @monarcode/effetch/test, and print the header each request
carried:
import * as from "effect/Effect";
import * as from "effect/http/HttpClientRequest";
import * as from "effect/Layer";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch/test";
const = .({
: "apiVersion",
: { : "2024-06-01" },
: (, ) =>
.(
.(, "api-version", ..),
),
});
class extends .<>()("Api", {
: "https://api.test",
: [],
}) {}
const = .("GET /reports");
const = .([
.(, () => .),
]);
const = .(function* () {
const = yield* ;
yield* .("/reports");
yield* .("/reports", {
: { : { : "2025-01-01" } },
});
for (const of yield* .) {
.(.["api-version"]);
}
}).(.(..(.())));
.();It prints the default version for the first call, and the call's own for the second:
2024-06-01
2025-01-01To learn more about the fake backend, see Test with a fake backend.
Hook reference
The rest of this page describes what a plugin can do: each hook, when it runs, and what it receives.
When each hook runs
A plugin can define any of the following hooks:
| Hook | When it runs | What it can do |
|---|---|---|
onRequest(request, ctx) | Before the request is sent, in list order. It has the full URL and the client's headers. | Return the request to send, changed or not, or fail. |
onResponse(response, ctx) | On every response, non-2xx included, in reverse list order. The status check and decoding come after every plugin's onResponse. | Return the response, changed or not, or fail. |
wrap(client, options, route) | Around its own onRequest and onResponse, every plugin after it and the network. A retrying wrap runs all of them on each attempt. | Retry, time out and the like. It can add errors, but can't remove them. |
onError(error, ctx) | After a call fails or dies, in list order, after the status check and decoding. | Observe only: it can't change the outcome. |
onExit(exit, ctx) | After every call, whatever the outcome, in list order, after the onError hooks. | Observe only: it can't change the outcome. |
To see the order the hooks of several plugins run in, see How plugins nest.
ctx.request is a different request in each hook:
- in
onRequest, the request the hook receives; - in
onResponse, the one this plugin passed on. Plugins after it may have changed it further, andresponse.requestis the one that was sent; - in
onErrorandonExit, the request as the call built it, before any plugin ran.
onError's error is the call's error: an Effetch error such as
HttpError, another plugin's error, one of the call's statusErrors, or a
defect.
- Neither runs when the call dies before its request is built, such as for
a missing path parameter or a body that can't be encoded. Neither runs for
requests sent through
api.httpClient, or for a plugin that the call skips withfalse. onErrordoesn't run when the call is interrupted, since that isn't a failure.onExitdoes, with the interruption in itsExit.- For a stream (
api.sse,api.ndjsonor a stream endpoint), the call ends when the response headers arrive.onExitruns then. Neither hook runs for the body being read, or for aDecodeErrorwhile it's read. - Neither hook can fail. If one dies, the defect is logged at the Debug level and ignored.
Record every call with onExit
onExit suits logging and metrics, and is what consoleLogger uses. This
plugin records each call's route, outcome and duration:
import * as from "effect/Effect";
import * as from "effect/Exit";
import { } from "@monarcode/effetch";
declare const : (: string, : boolean, : number) => void;
export const = .({
: "metrics",
: (, ) =>
.(() => (., .(), .)),
});The hook gets the call's Exit. On success, it holds the call's result: the
decoded output, or the response for a call without one. With
responseMode: "decoded-and-response", it holds a pair of both. Otherwise,
it holds the cause of the call's failure, defect or interruption.
Besides request, options and route, its ctx has:
response: the response the plugins returned. When a plugin failed after a response arrived, it's the last one the network sent, whose body may not have been read. It'sundefinedwhen no response arrived: after a network failure, a timeout, or a plugin that failed before the request was sent.durationMs: how long the call took, in whole milliseconds, retries included. It starts when the request enters the plugin chain, soonRequesthooks, such as reading a token, count. It stops after the status is checked and the body decoded, soonErrorhooks don't count.
The call returns after every onExit hook is done, and the hooks can't be
interrupted. Keep them quick, and fork anything slow.
Read the route
ctx.route is the call's method and path as written, before the params are
filled in: "GET /users/:id", whether the call was
api.get("/users/:id", …) or an endpoint. It's the same
for every user ID, so it's what to group logs, metrics and error reports by.
It's undefined for requests sent through api.httpClient.
A wrap reads it from its third argument, an Effect like options. The
following example reads the route in an onError hook and in a wrap:
import * as from "effect/Effect";
import * as from "effect/http/HttpClient";
import { } from "@monarcode/effetch";
declare const : (: unknown, : string | undefined) => void;
export const = .({
: "errorReporter",
: (, ) => .(() => (, .)),
});
export const = .({
: "timing",
: (, , ) =>
.(, (, ) =>
.(function* () {
const = (yield* ) ?? .;
return yield* .(, );
}),
),
});Tips
Keep these rules in mind as you write plugins:
- Services are required once. The services a plugin needs are
required by the client's layer (or
Fetch.make), not by each call. Services provided around a call win over those the client was built with. - Names are unique within a client. If two plugins have the same name,
building the client dies (with
Fetch.makeor the client's layer), with the messageTwo plugins are named "…". - Write
wrapbodies withEffect.gen. A ternary that returns two different Effects can't be typed. - Pass plugin lists inline, or let TypeScript infer them. Annotating a
list as
Fetch.Plugin.Any[]erases the plugins' types.
What's next
- Plugin recipes: copy a plugin that signs out on a
401, or one that sets a deadline with its own error. - Built-in plugins: decide where your plugin goes in the list.
- Change plugins for one call: skip or adjust your plugin on a single call.