Skip to main content

Authenticated API client

import { ApiClient } from "bytekit/api-client";

export function createApiClient(token: string) {
  return new ApiClient({
    baseUrl: "https://api.example.com",
    defaultHeaders: {
      Authorization: `Bearer ${token}`,
    },
  });
}

Deduplicate concurrent reads

import { ApiClient, RequestDeduplicator } from "bytekit";

const api = new ApiClient({ baseUrl: "https://api.example.com" });
const deduplicator = new RequestDeduplicator();

export function getCurrentUser() {
  return deduplicator.execute("/me", () => api.get("/me"));
}

Wrap a slow operation with timeout

import { withTimeout } from "bytekit/async";

const fetchReport = withTimeout(async (id: string) => {
  const response = await fetch(`/api/reports/${id}`);
  return response.json();
}, 5000);

Rate-limit outbound requests

import { ApiClient, RateLimiter } from "bytekit";

const limiter = new RateLimiter({
  maxRequests: 20,
  windowMs: 60_000,
});

const api = new ApiClient({
  baseUrl: "https://api.example.com",
  interceptors: {
    request: async (url, init) => {
      await limiter.waitForAllowance(url);
      return [url, init];
    },
  },
});

Validate API responses at the edge

import { ApiClient, zodAdapter } from "bytekit";
import { z } from "zod";

const ProjectSchema = z.object({
  id: z.string(),
  name: z.string(),
});

const api = new ApiClient({
  baseUrl: "https://api.example.com",
});

export async function getProject(id: string) {
  return api.get(`/projects/${id}`, {
    validateResponse: zodAdapter(ProjectSchema),
  });
}

Stream NDJSON data

import { StreamingHelper } from "bytekit";

await StreamingHelper.streamJsonLines("https://api.example.com/logs", {
  onChunk: (line) => {
    console.log("received", line);
  },
});
These recipes are intentionally small. Use them as starting points, then move into the focused guides for deeper configuration.