Hybrid setup
Sign in with your backend from the browser and call your API there, while the server keeps the session in its cookie.
Sometimes your backend's sign-in has to run in the browser, such as through a provider's SDK, or your pages call your API themselves. A hybrid setup lets the browser do both, while the server still keeps the session in its sealed cookie (encrypted with your secret, so only your server can read it), refreshes it, and renders who is signed in.
Two things change from a server-rendered setup:
- Signing in. The browser gets the tokens from your backend and sends
them to a server function, which seals them into the cookie with
session.signIn. - Calling your API. The session route (the route in your app that the
browser's client calls to read the session and sign out) gives the browser
the access token, and
createAuthFetchsends it. The refresh token stays in the cookie.
This page builds on the TanStack Start guide. Other frameworks lists what changes with Next.js and React Router.
Before you begin
- Follow the TanStack Start guide through
step 7. This page replaces four of its files:
src/auth/server.ts,src/auth/functions.ts,src/auth/client.tsandsrc/sign-in.ts. The rest stays as it is, including the sign-in route, which callssrc/sign-in.ts. - Your backend must allow requests from your site (CORS) for its sign-in and for the API calls the browser makes. Session kit's own requests go to your session route, on your site.
1. Let the session route serve the access token
clientCredentials: true lets the session route give the access token to
your own pages. Here's the guide's src/auth/server.ts with that option,
and without its login, which moves to the browser in the next step:
import "@tanstack/react-start/server-only";
import { } from "@monarcode/session-kit/server";
import { } from "@monarcode/session-kit/tanstack-start/server";
import { } from "zod";
export const = "https://dummyjson.com";
const = .({ : .(), : .() });
const = .({ : .(), : .() });
export const = ({
: "app",
: ,
: ..SESSION_SECRET!,
// The session route gives the access token to your own pages.
: true,
: async ({ , }) => {
const = await (`${}/auth/refresh`, {
: "POST",
,
: { "Content-Type": "application/json" },
: .({ }),
});
// DummyJSON rejected the refresh token: sign out.
if (. === 401 || . === 403) return null;
if (!.) throw new (`Refresh failed (${.})`);
return .(await .());
},
});
/** The session of the request Start is handling, found on each call. */
export const = ();2. Sign in with your backend in the browser
The browser calls your backend's sign-in, and gets the tokens and the user:
import { } from "zod";
export const = "https://dummyjson.com";
const = .({
: .(),
: .(),
});
export const = .({ : .(), : .() });
export type = <<typeof >>;
/** Signs in with your backend, from the browser. */
export async function (: string, : string) {
const = await (`${}/auth/login`, {
: "POST",
: { "Content-Type": "application/json" },
: .({ , }),
});
if (!.) throw new (`Sign-in failed (${.})`);
const : unknown = await .();
return { ....(), : .() };
}3. Send the tokens to the server
session.signIn seals what it's given, and never asks your backend. So the
server function decides what to trust. Check the tokens first, unless the
cookie's user is only ever shown.
Check the tokens first
The server function takes the tokens only, and asks your backend whose they are. A forged or expired access token is refused, and the cookie's user comes from your backend, not from the browser. The refresh token isn't checked until the first refresh:
import { } from "@tanstack/react-start";
import { } from "zod";
import { , } from "../backend";
import { } from "./server";
export const = ().(() =>
.(),
);
export const = ({ : "POST" })
.(.({ : .(), : .() }))
.(async ({ }) => {
// Your backend proves the access token is real, and says whose it is.
const = await (`${}/auth/me`, {
: { : `Bearer ${.}` },
});
if (!.) throw new ("Your backend refused the token");
const = .(await .());
return .({ ..., });
});The client's signIn takes what your backend's sign-in returned, and sends
only the tokens to signInFn:
import { } from "@monarcode/session-kit";
import type { } from "../backend";
import { , } from "./functions";
export function () {
return ({
: "app",
: null, // filled by loadSession, then by hydration
: "/api/session",
: () => (),
: ({ , }: ) =>
({ : { , } }),
});
}
export type = <typeof >;The form signs in with your backend, then with the client. The sign-in page's guard sends the user on, so the form doesn't navigate:
import type { } from "./auth/client";
import { } from "./backend";
/** Signs in, and resolves the message to show when it fails. */
export async function (
: ,
: string,
: string,
): <string | null> {
try {
await .(await (, ));
return null;
} catch () {
return instanceof ? . : "Could not sign in";
}
}With fromAccessToken as the server's user option, the server reads the
user from the access token instead. Give it a decode that verifies the
token's signature, and that's the check: see
Verify the token on a server.
Pass the tokens without a check
If the cookie's user is only ever shown, the server function can take the tokens and the user the browser sends, and seal them as they are:
import { } from "@tanstack/react-start";
import { } from "zod";
import { } from "../backend";
import { } from "./server";
export const = ().(() =>
.(),
);
export const = ({ : "POST" })
.(
.({
: .(),
: .(),
: ,
}),
)
.(({ }) => .());The client's signIn then sends everything your backend's sign-in
returned. src/sign-in.ts stays as it is:
import { } from "@monarcode/session-kit";
import type { } from "../backend";
import { , } from "./functions";
export function () {
return ({
: "app",
: null, // filled by loadSession, then by hydration
: "/api/session",
: () => (),
: (: ) => ({ : }),
});
}
export type = <typeof >;Anyone can then put any user in their own cookie, with tokens of their own. That's safe only when the cookie's user is shown, never trusted:
- Your backend authorizes every request with the access token, and
nothing on your server acts on
session.useralone, such as reading another account's data by itsid. - A forged token gets nowhere. Your API refuses it. At the first
refresh, your backend refuses its refresh token too, and a
refreshthat returnsnullfor that, as this guide's does, signs the user out.
When in doubt, check the tokens first. It costs one request at sign-in.
4. Call your API from the browser
createAuthFetch from @monarcode/session-kit/http sends the access token
that the session route serves. Make one per client, since the client is made
once per page load:
import { , } from "react";
import { } from "@monarcode/session-kit/http";
import { } from "@monarcode/session-kit/tanstack-router";
export function () {
const = ();
const = (
() => (, { : "https://dummyjson.com/" }),
[],
);
const [, ] = <number | null>(null);
async function () {
// DummyJSON's carts stand in for your orders.
const = await ("auth/carts");
if (!.) throw new (`Orders failed (${.})`);
const : unknown = await .();
const = ( as { ?: unknown } | null)?.;
(.() ? . : 0);
}
return (
<>
< ={() => void ().(() => {})}>Load orders</>
{ !== null && <>{} orders</>}
</>
);
}After a 401, the client asks the session route for a new access token, and the server refreshes with the cookie's refresh token. The access token in the browser says how the browser holds the token.
ky, axios and openapi-fetch can send their requests through authFetch:
see Other HTTP clients. Server functions
can still call your API too, as the guide's
Call your API shows.
Other frameworks
With Next.js or React Router, the steps are the same. What changes is where each piece lives, and how the session reaches the browser after sign-in.
In the Next.js guide's app:
- Add
clientCredentials: trueinlib/auth/server.ts. - Have
signInActioninapp/actions.tstake the tokens, check them as in step 3, and callsession.signIn. - The client in
lib/auth/client.tsalready reads the session throughendpoint, with norevalidate. ItssignInoption callssignInActionwith the tokens. - Components get the client with
useAuthClientfrom@monarcode/session-kit/react.
In the React Router with server rendering guide's app:
- Add
clientCredentials: trueinapp/auth/session.server.ts. - Give the sign-in route an action that takes the tokens, checks them as in
step 3, and calls
auth(context).signIn. - After your backend's sign-in, submit the tokens to that action from the
browser, such as with
useSubmit. React Router runs the loaders again, anduseMirrorAuthtakes the new session. - Components get the client with
useAuthClientfrom@monarcode/session-kit/react.
Things to know
- The refresh token passes through page scripts during sign-in, in your backend's sign-in response, on its way to your server. Session kit's client passes it on without keeping it, and never holds it again. A provider's SDK may keep its own copy: check its storage settings. If your backend's sign-in can run on the server, sign in there, as the setup guides do.
- Signing out works as in the guide's
Sign out step, through the
session route. To end the session at your backend too, give
createServerAutharevoke.
Next steps
- Your backend decides what's allowed: what the cookie's user can be trusted for.
- The access token in the browser: how page scripts get and renew the access token.
- Other HTTP clients: send ky, axios or
openapi-fetch requests through
authFetch. - Server sessions: the cookie, its secret and the limits every server-rendered setup shares.
Server sessions
What every server-rendered setup shares, from the cookie and its secret to refreshing before rendering, signing out and limits.
Effect and effetch
Read the session as an Effect service, and call your API with effetch's sessionBearer plugin, which sends the access token and renews it after a 401.