Browse recipes

Compose API clients by domain

Share one request configuration across auth, users and billing domains.

Table of contents

APIs used

request
Provides the asynchronous Valyrian.js HTTP client entry point.

Run this recipe

Starting project
Start with a Valyrian.js TypeScript project that imports the Request module.
File
Place the snippet in src/api.ts and import createApiClients from the browser or server entry that owns the clients.
Run
Run the project's TypeScript build and execute that entry. The standalone call logs the keys returned by createApiClients.
Observable result
The output contains authApi, usersApi, billingApi and destroy, and each domain client inherits the root options.

Create domain clients

Create the root client once per browser context or once inside each ServerStorage.run request boundary on the server.

js
import { request } from "valyrian.js/request";

export function createApiClients(token) {
  const rootApi = request.new("", {
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + token,
    },
  });

  const requestIdPlugin = rootApi.use({
    request(ctx) {
      ctx.options.headers["X-Request-Id"] = crypto.randomUUID();
      return ctx;
    },
  });

  return {
    authApi: rootApi.new("/api/auth"),
    usersApi: rootApi.new("/api/users"),
    billingApi: rootApi.new("/api/billing"),
    destroy() {
      rootApi.eject(requestIdPlugin);
    },
  };
}

const clients = createApiClients("example-token");
console.log(Object.keys(clients));
clients.destroy();

Result

The result exposes authApi, usersApi and billingApi with inherited root options. destroy ejects the shared plugin.

Continue