Getting started
Build a small app that signs in, stays signed in across reloads and tabs, calls an API, and signs out.
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, 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 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 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:
import { } from "zod";
export const = "https://dummyjson.com";
export const = .({
: .(),
: .(),
: .(),
: .(),
});
const = .({
: .(),
: .(),
});
const = (: string, : unknown, ?: RequestInit) =>
( + , {
...,
: "POST",
: { "Content-Type": "application/json" },
: .(),
});
/** Checks the password, and resolves the tokens and the user. */
export async function (: string, : string) {
const = await ("/auth/login", { , });
if (!.) throw new (`Sign-in failed (${.})`);
// DummyJSON returns the user's fields beside the tokens.
const : unknown = await .();
return { ....(), : .() };
}
/**
* Exchanges a refresh token for new tokens. Resolves `null` when the backend
* rejects the token, and throws for any other failure.
*/
export async function (: string, : ) {
const = await ("/auth/refresh", { }, { });
// DummyJSON answers 403 for an invalid token and 401 for a missing one.
if (. === 401 || . === 403) return null;
if (!.) throw new (`Refresh failed (${.})`);
return .(await .());
}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:
import { , } from "@monarcode/session-kit";
import { , , } from "./backend.js";
export const = ({
// Keeps this app's saved session apart from any other on the same origin.
: "my-app",
// Every user is checked against this schema, and typed by it.
: ,
// Where the session is saved: `localStorage`.
: (),
// How expired access is replaced.
: ({ , }) => (, ),
});
/** Signs in with the backend, then hands the result to Session kit. */
export async function (: string, : string) {
const = await (, );
await .();
}
export type = typeof ;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:
nullmeans 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 has the details, and 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 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:
import { , type } from "react";
import { } from "./auth.js";
export function () {
const [, ] = ("");
const [, ] = (false);
async function (: <>) {
.();
const = new (.);
("");
(true);
try {
await (
(.("username")),
(.("password")),
);
} catch () {
( instanceof ? . : "Could not sign in");
} finally {
(false);
}
}
return (
< ={}>
<>Sign in</>
{/* DummyJSON's documented test user. */}
<>
Username
< ="username" ="emilys" ="username" />
</>
<>
Password
<
="password"
="password"
="emilyspass"
="current-password"
/>
</>
{ && < ="alert">{}</>}
< ={}>{ ? "Signing in…" : "Sign in"}</>
</>
);
}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. By the last case, TypeScript has narrowed
user, so it's never null there:
import {
,
,
,
} from "@monarcode/session-kit/react";
import { } from "./auth.js";
import { } from "./sign-in.js";
// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
interface Register {
: typeof ;
}
}
export function () {
return (
< ={}>
< />
< />
</>
);
}
function () {
const { , } = ();
const = ();
switch () {
case "initializing":
return <>Restoring your session…</>;
case "unauthenticated":
return < />;
case "unavailable":
// Access couldn't be restored or refreshed: offer another try.
return (
< ={() => void .().(() => {})}>
Try again
</>
);
default:
// Signed in: "authenticated", or "refreshing" with the user on screen.
return (
<>
<>Welcome, {.}</>
< ={() => void .().(() => {})}>
Sign out
</>
</>
);
}
}
/** The latest failure, such as a refresh the backend couldn't answer. */
function () {
const = (() => .);
return ? < ="alert">{.}</> : null;
}Each part of this file has a job:
AuthProvidermounts 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, asAuthErrorMessagedoes.useAuthClient()returns the client, for actions such asretryandsignOut.AuthErrorMessageshowsstate.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 covers where each failure appears.
Two more helpers are useful as the app grows:
isSignedIn(state), from@monarcode/session-kit, istruewhile the status isauthenticatedorrefreshing. Pass it touseAuthto 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, give locked a case of its own. It
has a user too, but no usable access.
That's a working app. To check it:
- Sign in. The welcome message appears.
- Reload the page. You're still signed in.
- 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:
import { } from "@monarcode/session-kit/http";
import { } from "./auth.js";
import { , } from "./backend.js";
export const = (, { : `${}/` });
/** The signed-in user, fresh from the backend. */
export async function () {
const = await ("auth/me");
if (!.) throw new (`Profile failed (${.})`);
return .(await .());
}When a request gets a 401, authFetch refreshes, then sends a GET or
HEAD again. It never sends other methods twice.
Authenticated requests covers the rest of its
behavior and its options.
To see it work, add a button that loads the profile:
import { } from "react";
import { } from "./api.js";
export function () {
const [, ] = ("");
const [, ] = ("");
async function () {
("");
try {
((await ()).);
} catch () {
( instanceof ? . : "Could not load");
}
}
return (
<>
< ={() => void ()}>Load my profile</>
{ && <>{}</>}
{ && < ="alert">{}</>}
</>
);
}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 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, and TanStack Start in SPA mode.
- React Router, in declarative, data, or
framework mode with
ssr: false. - Expo Router, for iOS and Android. Its guide starts from scratch.
- Without a router, you're done. Render by
status, asScreendoes.
With Effect, the same client becomes a service: see Effect and effetch.
Next steps
- Using the client: what else the client does, such as updating the user and locking.
- Configuring the client: the rest of its options.
- Security: what Session kit protects, and what stays your backend's job.