@mrzr/api-client

Plugins

Extend @mrzr/api-client with plugins. Call several APIs on one session with the services plugin, or write your own with four small hooks.

Plugins are optional. Each one is a separate import, so you only ship the ones you use.

services: several APIs, one login

import { createClient } from "@mrzr/api-client";
import { services } from "@mrzr/api-client/services";

const api = createClient({
  baseUrl: "https://api.example.com",
  plugins: [
    services({
      files: "https://files.example.com",
      search: { baseUrl: "https://search.example.com", timeout: 5_000 },
      maps: { baseUrl: "https://maps.thirdparty.com", auth: false },
    }),
  ],
});

await api.service("files").get("/uploads");
api.service("fiels");   // type error: not a declared service

Every service shares the client's session, refresh and cancellation. A service gets the token unless you set auth: false, which you should for third-party APIs.

OptionDefaultMeaning
baseUrlrequiredWhere the service lives
authtrueSend the token and refresh on 401
timeoutclient'sDefault timeout for this service
headers–Added to every call

If two APIs need different logins, create two clients with different storageKeys instead.

Writing a plugin

A plugin is an object with a name and any of four hooks:

import type { ApiPlugin } from "@mrzr/api-client";

const traceIds: ApiPlugin = {
  name: "trace-ids",
  beforeRequest: (request) => ({
    ...request,
    config: {
      ...request.config,
      headers: { ...request.config?.headers, "X-Trace-Id": crypto.randomUUID() },
    },
  }),
};

createClient({ baseUrl, plugins: [traceIds] });
HookRunsUse it to
configure(options)Once, before the client is createdChange client options
beforeRequest(request)Before each get/post/put/patch/deleteRewrite the URL, body or config
afterResponse(result, request)After each of those callsReshape results, collect metrics
extend(client)Once, after the client is createdAdd methods, like api.service()

Plugins run in the page, so they never see the access token. A plugin that throws fails only that one call, with an error naming the plugin. login, logout and refresh don't pass through plugins.

On this page