@mrzr/api-client

Quick Start

Install @mrzr/api-client, create one client, make typed requests, handle errors and log users in. Everything you need for a first working setup.

1. Install

npm install @mrzr/api-client

2. Create one client and export it

lib/api.ts
import { createClient } from "@mrzr/api-client";

export const api = createClient({
  baseUrl: "https://api.example.com",
  loginUrl: "/auth/login",       // these three are the defaults
  refreshUrl: "/auth/refresh",
  logoutUrl: "/auth/logout",
});

Create it once and import it everywhere. Every client owns its own session.

3. Make requests

import { api } from "./lib/api";

const { data } = await api.get<User[]>("/users", { params: { page: 1 } });
await api.post("/users", { name: "Ada" });

4. Handle errors

A failed request throws an ApiError:

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

try {
  await api.post("/users", { name: "" });
} catch (e) {
  if (e instanceof ApiError) {
    console.log(e.statusCode);   // 422
    console.log(e.errors);       // { name: ["is required"] }
  }
}

5. Log in and out

await api.login({ email, password });   // POST /auth/login, tokens stored
await api.logout();                     // POST /auth/logout, every tab logged out

api.onAuthStateChange((state) => {
  if (!state.isAuthenticated) router.push("/login");
});

The client finds the tokens in the login response by itself: access, accessToken, access_token, token and jwt are all recognised, at the top level or inside data, tokens, result or payload. If your server uses other names, see Token refresh.

That's it. Refresh, worker isolation and tab sync are already on.

On this page