# Getting started (https://session-kit.pages.dev/docs/getting-started)

Your backend signs users in and answers with an access token and a refresh
token. In this tutorial, you build a small React app around those tokens. It
signs in, stays signed in across reloads and tabs, calls an API with the
access token, and signs out.

The code signs in against
[DummyJSON's auth API](https://dummyjson.com/docs/auth), a public test
backend, so it runs as written. The web router guides build on this app. If
your app renders on the server, it creates its client differently: start
from [Server rendering](https://session-kit.pages.dev/docs/server-rendering) instead.

## Before you begin

- A React app. A router is optional: step 6 links to the guide for yours.
- Session kit and Zod, installed as [Installation](https://session-kit.pages.dev/docs/installation)
  shows.

## 1. Talk to your backend

Session kit never calls your backend for you, so start with the two requests
you'd write anyway. One signs in, and the other exchanges a refresh
token for new tokens. Nothing in this file imports Session kit:

```ts title="src/backend.ts"
import { z } from "zod";

export const API = "https://dummyjson.com";

export const userSchema = z.object({
  id: z.number(),
  username: z.string(),
  email: z.string(),
  firstName: z.string(),
});

const tokensSchema = z.object({
  accessToken: z.string(),
  refreshToken: z.string(),
});

const post = (path: string, body: unknown, init?: RequestInit) =>
  fetch(API + path, {
    ...init,
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });

/** Checks the password, and resolves the tokens and the user. */
export async function login(username: string, password: string) {
  const response = await post("/auth/login", { username, password });
  if (!response.ok) throw new Error(`Sign-in failed (${response.status})`);
  // DummyJSON returns the user's fields beside the tokens.
  const body: unknown = await response.json();
  return { ...tokensSchema.parse(body), user: userSchema.parse(body) };
}

/**
 * Exchanges a refresh token for new tokens. Resolves `null` when the backend
 * rejects the token, and throws for any other failure.
 */
export async function refresh(refreshToken: string, signal: AbortSignal) {
  const response = await post("/auth/refresh", { refreshToken }, { signal });
  // DummyJSON answers 403 for an invalid token and 401 for a missing one.
  if (response.status === 401 || response.status === 403) return null;
  if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
  return tokensSchema.parse(await response.json());
}
```

The schemas do two jobs. They check what the backend sent, and they give the
rest of the app its types.

DummyJSON's docs add `credentials: "include"` to these requests, to send its
cookies. This file leaves it out: Session kit keeps the tokens in storage,
not in cookies, and in step 5 `authFetch` adds the access token to your API
calls.

## 2. Create the client

The client is the one object that holds the session. Tell it what a user is,
where to save the session, and how to refresh:

```ts title="src/auth.ts"
import { createAuth, webStorage } from "@monarcode/session-kit";

import { login, refresh, userSchema } from "./backend.js";

export const auth = createAuth({
  // Keeps this app's saved session apart from any other on the same origin.
  name: "my-app",
  // Every user is checked against this schema, and typed by it.
  user: userSchema,
  // Where the session is saved: `localStorage`.
  storage: webStorage(),
  // How expired access is replaced.
  refresh: ({ refreshToken, signal }) => refresh(refreshToken, signal),
});

/** Signs in with the backend, then hands the result to Session kit. */
export async function signInWithPassword(username: string, password: string) {
  const tokens = await login(username, password);
  await auth.signIn(tokens);
}

export type AppAuth = typeof auth;
```

Create the client one time, at module level, as this file does. If an app has
more than one client, give each its own `name`.

`refresh` tells two failures apart, so an outage doesn't sign anyone out:

- `null` means the backend rejected the refresh token, so the user is signed
  out.
- A throw means something else failed, such as the network. The session is
  kept, and the error reported.

[Refresh](https://session-kit.pages.dev/docs/configuration/refresh) has the details, and
[Storage](https://session-kit.pages.dev/docs/configuration/storage) lists the other places a session can
be saved.

DummyJSON's tokens are JWTs, so their expiry comes from the `exp` and `iat`
claims. [Expiry](https://session-kit.pages.dev/docs/configuration/expiry) covers backends that say it
another way.

## 3. Add a sign-in form

The form calls `signInWithPassword` from `src/auth.ts`, and has no Session
kit code of its own:

```tsx title="src/sign-in.tsx"
import { useState, type FormEvent } from "react";

import { signInWithPassword } from "./auth.js";

export function SignIn() {
  const [error, setError] = useState("");
  const [pending, setPending] = useState(false);

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    setError("");
    setPending(true);
    try {
      await signInWithPassword(
        String(form.get("username")),
        String(form.get("password")),
      );
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "Could not sign in");
    } finally {
      setPending(false);
    }
  }

  return (
    <form onSubmit={submit}>
      <h1>Sign in</h1>
      {/* DummyJSON's documented test user. */}
      <label>
        Username
        <input name="username" defaultValue="emilys" autoComplete="username" />
      </label>
      <label>
        Password
        <input
          name="password"
          type="password"
          defaultValue="emilyspass"
          autoComplete="current-password"
        />
      </label>
      {error && <p role="alert">{error}</p>}
      <button disabled={pending}>{pending ? "Signing in…" : "Sign in"}</button>
    </form>
  );
}
```

The form doesn't navigate after it signs in. Signing in changes the client's
state, and the next step renders from that state. With a router, the sign-in
page's guard runs again and sends the user on.

## 4. Read the session in React

The hooks come from `@monarcode/session-kit/react`. Register your client's
type one time, in the file that renders `AuthProvider`, and the hooks carry
your user's type.

Then render by `status`. Each case is one of the states in
[How it works](https://session-kit.pages.dev/docs#how-it-works). By the last case, TypeScript has narrowed
`user`, so it's never `null` there:

```tsx title="src/app.tsx"
import {
  AuthProvider,
  useAuth,
  useAuthClient,
} from "@monarcode/session-kit/react";

import { auth } from "./auth.js";
import { SignIn } from "./sign-in.js";

// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
  interface Register {
    auth: typeof auth;
  }
}

export function App() {
  return (
    <AuthProvider client={auth}>
      <AuthErrorMessage />
      <Screen />
    </AuthProvider>
  );
}

function Screen() {
  const { status, user } = useAuth();
  const client = useAuthClient();

  switch (status) {
    case "initializing":
      return <p>Restoring your session…</p>;
    case "unauthenticated":
      return <SignIn />;
    case "unavailable":
      // Access couldn't be restored or refreshed: offer another try.
      return (
        <button onClick={() => void client.retry().catch(() => {})}>
          Try again
        </button>
      );
    default:
      // Signed in: "authenticated", or "refreshing" with the user on screen.
      return (
        <main>
          <h1>Welcome, {user.firstName}</h1>
          <button onClick={() => void client.signOut().catch(() => {})}>
            Sign out
          </button>
        </main>
      );
  }
}

/** The latest failure, such as a refresh the backend couldn't answer. */
function AuthErrorMessage() {
  const error = useAuth((state) => state.error);
  return error ? <p role="alert">{error.message}</p> : null;
}
```

Each part of this file has a job:

- `AuthProvider` mounts the client. It restores the saved session, starts the
  refresh timer, and follows other tabs.
- `useAuth()` returns the whole state. `useAuth(selector)` returns a part of
  it, and re-renders only when that part changes, as `AuthErrorMessage` does.
- `useAuthClient()` returns the client, for actions such as `retry` and
  `signOut`.
- `AuthErrorMessage` shows `state.error`, where failures appear.

The buttons ignore a rejection because `AuthErrorMessage` already shows the
failure. `retry` rejects when it fails, and the failure also appears in
`state.error`. `signOut` signs the user out even when your backend can't
revoke the tokens: that failure only appears in `state.error`. `signOut`
rejects only when it can't clear the saved session.
[Errors](https://session-kit.pages.dev/docs/configuration/errors) covers where each failure appears.

Two more helpers are useful as the app grows:

- `isSignedIn(state)`, from `@monarcode/session-kit`, is `true` while the
  status is `authenticated` or `refreshing`. Pass it to `useAuth` to read only
  that: `useAuth(isSignedIn)`.
- With more than one client in an app, create hooks for each with
  `createAuthHooks<typeof client>()` instead of registering one.

With [`locking`](https://session-kit.pages.dev/docs/client/locking), give `locked` a case of its own. It
has a user too, but no usable access.

That's a working app. To check it:

1. Sign in. The welcome message appears.
2. Reload the page. You're still signed in.
3. Open the app in a second tab, and sign out in one of them. Both tabs show
   the sign-in form.

## 5. Call your API

Your API wants the access token on each request. `createAuthFetch` makes a
`fetch` that adds it, and sends it to your API's origin and to no other:

```ts title="src/api.ts"
import { createAuthFetch } from "@monarcode/session-kit/http";

import { auth } from "./auth.js";
import { API, userSchema } from "./backend.js";

export const authFetch = createAuthFetch(auth, { baseUrl: `${API}/` });

/** The signed-in user, fresh from the backend. */
export async function fetchProfile() {
  const response = await authFetch("auth/me");
  if (!response.ok) throw new Error(`Profile failed (${response.status})`);
  return userSchema.parse(await response.json());
}
```

When a request gets a 401, `authFetch` refreshes, then sends a `GET` or
`HEAD` again. It never sends other methods twice.
[Authenticated requests](https://session-kit.pages.dev/docs/client/requests) covers the rest of its
behavior and its options.

To see it work, add a button that loads the profile:

```tsx title="src/profile.tsx"
import { useState } from "react";

import { fetchProfile } from "./api.js";

export function ProfileButton() {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");

  async function load() {
    setError("");
    try {
      setEmail((await fetchProfile()).email);
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "Could not load");
    }
  }

  return (
    <section>
      <button onClick={() => void load()}>Load my profile</button>
      {email && <p>{email}</p>}
      {error && <p role="alert">{error}</p>}
    </section>
  );
}
```

Render `<ProfileButton />` in `Screen`'s signed-in case, under the welcome
message. Sign in, then select **Load my profile**. Emily's email address
appears, from a request that carried the access token.

ky, axios and openapi-fetch can each send their requests through
`authFetch`. [Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients) shows
how for each one.

## 6. Protect your routes

The client is the same everywhere. What changes is how each router keeps
signed-out users away from private pages. To continue, follow the guide for
your router:

- [TanStack Router](https://session-kit.pages.dev/docs/setups/tanstack-router), and
  [TanStack Start in SPA mode](https://session-kit.pages.dev/docs/setups/tanstack-router#tanstack-start-in-spa-mode).
- [React Router](https://session-kit.pages.dev/docs/setups/react-router), in declarative, data, or
  framework mode with `ssr: false`.
- [Expo Router](https://session-kit.pages.dev/docs/setups/expo), for iOS and Android. Its guide starts from
  scratch.
- Without a router, you're done. Render by `status`, as `Screen` does.

With Effect, the same client becomes a service: see
[Effect and effetch](https://session-kit.pages.dev/docs/effect).

## Next steps

- [Using the client](https://session-kit.pages.dev/docs/client): what else the client does, such as
  updating the user and locking.
- [Configuring the client](https://session-kit.pages.dev/docs/configuration): the rest of its options.
- [Security](https://session-kit.pages.dev/docs/security): what Session kit protects, and what stays your
  backend's job.