chowbea-axios
More Examples

Svelte

Use chowbea-axios typed Axios clients in Svelte and SvelteKit with Result-based calls.

Svelte doesn't care that your client is Axios. It cares that your data shows up reactively and errors aren't swallowed. Same contracts, same api.op.

For Vite apps, set env_accessor = "import.meta.env" and base_url_env = "VITE_API_URL".

Component fetch

UserList.svelte
<script lang="ts">
  import { onMount } from "svelte";
  import { api } from "$lib/api/api.client";
  import type { UserDto } from "$lib/api/_generated/api.contracts";
  import type { ApiError } from "$lib/api/api.error";

  let users: UserDto[] | null = $state(null);
  let error: ApiError | null = $state(null);
  let loading = $state(true);

  onMount(async () => {
    const result = await api.op.listUsers();
    loading = false;
    if (result.error) {
      error = result.error;
      return;
    }
    users = result.data;
  });
</script>

{#if loading}
  <p>Loading…</p>
{:else if error}
  <p role="alert">{error.message}</p>
{:else}
  <ul>
    {#each users ?? [] as user (user.id)}
      <li>{user.email}</li>
    {/each}
  </ul>
{/if}

(If you're on Svelte 4, swap $state for let — the API calls stay identical.)

SvelteKit load

routes/users/+page.ts
import { api } from "$lib/api/api.client";
import { error } from "@sveltejs/kit";
import type { PageLoad } from "./$types";

export const load: PageLoad = async () => {
  const { data, error: apiError } = await api.op.listUsers();
  if (apiError) {
    error(apiError.status ?? 500, apiError.message);
  }
  return { users: data };
};
routes/users/+page.svelte
<script lang="ts">
  import type { PageData } from "./$types";
  let { data }: { data: PageData } = $props();
</script>

<ul>
  {#each data.users as user (user.id)}
    <li>{user.email}</li>
  {/each}
</ul>

Browser-only APIs (localStorage auth) belong in client loads or components — not in universal load unless you've made the instance SSR-safe.

Shared unwrap

lib/api/unwrap.ts
import type { Result } from "$lib/api/api.error";

export async function unwrap<T>(promise: Promise<Result<T>>): Promise<T> {
  const { data, error } = await promise;
  if (error) throw error;
  return data;
}

Throwing ApiError from load pairs nicely with SvelteKit's error() helper when you map status.

Next Steps

On this page