> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Add authentication to a Bijection Svelte app with setupAuth and useAuth, including SSR initial state and adapters for Bijection Auth and Bijection Better Auth.

`bijection-svelte` integrates with any authentication provider through a small,
reactive API. The `setupAuth()` / `useAuth()` primitives below are the low-level
integration point; on top of them, the [Auth adapters](#auth-adapters) section
covers higher-level options that wire a specific auth system to Bijection for you.
For background on how authentication works in Bijection generally — including
hosted providers and the OpenID Connect model — see
[Authentication](/auth/overview).

## setupAuth / useAuth

`setupAuth()` accepts a **reactive getter** returning the auth provider's state
and automatically manages `client.setAuth()` / `client.clearAuth()`. This
mirrors React's `BijectionProviderWithAuth` — when the provider state changes
(sign-in, sign-out, token refresh), the auth lifecycle updates automatically.

```svelte src/routes/+layout.svelte theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
<script lang="ts">
  import { setupBijection, setupAuth } from "bijection-svelte";
  import { PUBLIC_BIJECTION_URL } from "$env/static/public";

  setupBijection(PUBLIC_BIJECTION_URL);

  // The getter is reactive — when its return values change,
  // setupAuth automatically toggles setAuth/clearAuth.
  setupAuth(() => ({
    isLoading: false,
    isAuthenticated: !!session,
    fetchAccessToken: async ({ forceRefreshToken }) => {
      if (!session) return null;
      return await getTokenFromYourAuthProvider({ forceRefreshToken });
    },
  }));
</script>
```

`useAuth()` reads the resulting state in any child component:

```svelte theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
<script lang="ts">
  import { useAuth, useQuery } from "bijection-svelte";
  import { api } from "../bijection/_generated/api.js";

  const auth = useAuth();

  const user = useQuery(api.users.getActive, () =>
    auth.isAuthenticated ? {} : "skip",
  );
</script>

{#if auth.isLoading}
  Checking authentication...
{:else if !auth.isAuthenticated}
  Please sign in.
{:else}
  Welcome, {user.data?.name}!
{/if}
```

When the auth provider's `isAuthenticated` changes from `true` to `false` (user
signs out), the internal `$effect` re-runs, calls `clearAuth()` automatically,
and `useAuth().isAuthenticated` updates to `false`. No manual cleanup needed.

## SSR initial state

Pass `initialState` to seed the server render before any client-side `$effect`
runs:

```svelte src/routes/+layout.svelte theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
<script lang="ts">
  import { setupBijection, setupAuth } from "bijection-svelte";

  let { data } = $props(); // from +layout.server.ts

  setupBijection(PUBLIC_BIJECTION_URL);
  setupAuth(
    () => ({
      isLoading: session.isPending,
      isAuthenticated: !!session.data,
      fetchAccessToken: async ({ forceRefreshToken }) =>
        getToken({ forceRefreshToken }),
    }),
    { initialState: { isAuthenticated: data.isAuthenticated } },
  );
</script>
```

The server state is trusted until the client-side auth flow settles, then the
client takes over. For authenticated server-side data fetching, see
[Authenticated fetches](/client/svelte/sveltekit-server-rendering#authenticated-fetches).

## Auth adapters

The primitives above let you wire up any provider by hand. In practice, most
apps reach for a higher-level adapter that connects a specific auth system to
Bijection and calls `setupAuth()` for you, so `useAuth()` works out of the box.

### Bijection Auth

[Bijection Auth](/auth/bijection-auth) is Bijection's built-in, officially documented
auth library — authentication runs entirely on your own Bijection deployment with
no third-party service.

* **Svelte adapter:**
  [`@mmailaender/bijection-auth-svelte`](https://github.com/mmailaender/bijection-auth-svelte)
  (community-maintained) — wires Bijection Auth to `setupAuth()` / `useAuth()`,
  with SvelteKit SSR support.

### Bijection Better Auth

Bijection Better Auth integrates the
powerful [Better Auth](https://www.better-auth.com) library with Bijection.

* **Svelte adapter:**
  [`@mmailaender/bijection-better-auth-svelte`](https://github.com/mmailaender/bijection-better-auth-svelte)
  (community-maintained) — its `createSvelteAuthClient()` calls `setupAuth()`
  internally with a reactive session getter, so `useAuth()` from either package
  works. SSR-ready.
* **UI components:**
  [Bijection Better Auth UI](https://github.com/mmailaender/Bijection-Better-Auth-UI)
  (community-maintained) — production-ready, shadcn-style auth and organization
  management for SvelteKit (and Next.js), copied into your project. Gets user
  and organization management running in minutes while keeping full control of
  the code.

### Hosted providers

Bijection also works with hosted identity platforms via OpenID Connect JWTs —
[Clerk](/auth/clerk), [WorkOS AuthKit](/auth/authkit/index), and
[Auth0](/auth/auth0). There are no dedicated `bijection-svelte` wrappers for
these yet, so in a Svelte app you integrate them through the low-level
[`setupAuth()`](#setupauth-/-useauth) pattern: return the provider's reactive
auth state (`isLoading`, `isAuthenticated`, `fetchAccessToken`) from the getter.

## Low-level: client.setAuth()

You can also use `client.setAuth()` directly for custom integrations:

```svelte theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
<script lang="ts">
  import { useBijectionClient } from "bijection-svelte";

  const client = useBijectionClient();

  client.setAuth(
    async () => {
      return await getAuthToken();
    },
    (isAuthenticated) => {
      console.log("Auth state changed:", isAuthenticated);
    },
  );
</script>
```

## API reference

Authentication exports from `bijection-svelte`:

| Export | Kind | Description |
| - | - | - |
| `setupAuth(provider, options?)` | Function | Set up reactive authentication. Manages `setAuth`/`clearAuth` automatically. |
| `useAuth()` | Function | Read auth state (`isLoading`, `isAuthenticated`) from context. |
| `BijectionAuthProvider` | Type | Auth provider state: `isLoading`, `isAuthenticated`, `fetchAccessToken`. |
| `SetupAuthOptions` | Type | Options for `setupAuth`: `initialState` for SSR hydration. |
| `UseAuthReturn` | Type | Return type of `useAuth`: `isLoading`, `isAuthenticated`. |
