SPA (no backend)
Add sign-in to a pure single-page app — Vite, Create React App, a static site — with no server of your own and no tokens in JavaScript. Foir sets an HttpOnly session cookie on your own domain; your SPA silently exchanges it for a short-lived access token that never leaves memory.
This gives a backend-less SPA the same security posture as a session held on your own server, without the server.
Note: This requires a custom login domain on the same registrable domain as your app — for example an app on
app.acme.comand login onlogin.acme.com. That is what makes the session cookie first-party to your app. If you can’t add DNS records, use the Quickstart token flow instead and hold the access token in memory.
How it works
Browser (app.acme.com) Foir (login.acme.com) Foir (api.foir.dev)
│ │ │
│ no session → redirect to login │ │
│───────────────────────────────────────►│ │
│ …user authenticates (pwd/OTP/OAuth)… │ │
│ ◄── 302 back to app │ │
│ Set-Cookie: foir_session │ │
│ HttpOnly; Secure; SameSite=Lax │ │
│ Domain=.acme.com │ │
│ │ │
│ GET /session/token (cookie sent) │ │
│───────────────────────────────────────►│ │
│ ◄── { access_token, expires_in: 900 } │ │
│ │ │
│ POST /graphql Authorization: Bearer <access_token> │
│─────────────────────────────────────────────────────────────────────►│Two credentials, deliberately unequal:
- The session cookie is long-lived and
HttpOnly, so JavaScript cannot read it and cross-site scripting cannot steal it. It is a session credential only — it never authenticates a data call. It slides over a 30-day idle window and is capped at 90 days from first login; both defaults, both settable per project — see Session windows. - The access token lives 15 minutes and is held in memory by the SDK. It is never written to
localStorage,sessionStorage, or a cookie. If it leaks, it expires.
There is no refresh token anywhere in this flow. Re-exchanging the cookie is the refresh.
1. Register an auth client
In your Foir config, give the auth client your app’s redirect URI, a custom login domain, and the origins your SPA runs on:
defineAuthClient({
clientId: 'acme-spa',
name: 'Acme',
redirectUris: ['https://app.acme.com/callback'],
customDomains: ['login.acme.com'],
postLoginUrl: 'https://app.acme.com',
allowedOrigins: ['https://app.acme.com'],
});Run foir push. This registers the domain and prints two DNS records to publish:
CNAME login.acme.com -> login-edge.foir.dev
TXT _foir-challenge.login.acme.com -> <token>They do different jobs and you need both. The TXT proves you own the domain, and is what verification checks. The CNAME is what actually routes the login. Publish only the TXT and the domain verifies while the hostname resolves nowhere — the most confusing way this can fail, because every status says success.
Until the domain is verified, no session cookie is issued.
allowedOrigins is what lets the browser exchange the cookie for a token. It is an exact allowlist, matched like redirectUris: scheme and host (and port, if it isn’t 443), https only, no wildcards, no paths. List every origin your app is served from — including any preview or staging origin that needs to sign in.
Note: There is no domain-wide default. Granting every origin on
acme.comwould also grant a subdomain you no longer control, or one serving user-generated content — either could then mint your users’ access tokens. So if you list nothing here, the browser session doesn’t work, andgetToken()returnsnull. If that’s what you’re seeing, this is the first thing to check.
You can also set all of this on the auth client in the console, under Access → Sign-in → Auth Clients.
See Config reference for the full defineAuthClient surface.
2. Wrap your app
import { FoirProvider } from '@foir/sdk/react';
export function Root() {
return (
<FoirProvider
env={{
PLATFORM_API_URL: 'https://api.foir.dev/graphql',
PLATFORM_API_KEY: 'foir_pub_…',
}}
hostedSession={{ loginOrigin: 'https://login.acme.com' }}
>
<App />
</FoirProvider>
);
}hostedSession replaces the default token store. With it set, the SDK holds nothing in localStorage.
3. Sign in and out
Sign-in is a redirect, not a form — Foir renders the login UI on your domain:
import { useFoirSession, useFoirAuth } from '@foir/sdk/react';
function Header() {
const { isAuthenticated, isLoading } = useFoirSession();
const { hostedSignInUrl, signOut } = useFoirAuth();
if (isLoading) return null;
if (isAuthenticated) return <button onClick={() => signOut()}>Sign out</button>;
// Null unless the provider was given `hostedSession`.
if (!hostedSignInUrl) return null;
return <a href={hostedSignInUrl()}>Sign in</a>;
}hostedSignInUrl() sends the user to your login domain and returns them to where they were. signOut() revokes the session server-side and clears the cookie.
Where a user is returned
After signing in, the user lands on postLoginUrl, carrying the page they asked for as returnTo when it is one Foir may send them to:
- a path, which rides on
postLoginUrl’s own origin; - an address on
postLoginUrl’s origin; - an address on one of
allowedOrigins; - any address under the app base URL in force for the sign-in: the organization’s, else the nearest organization above it that sets one, else the project’s. Same scheme and host, and a path beneath its path.
The last rule is what lets one auth client serve an app with an address per organization. Name the organization with the org parameter (or sign in on a login domain bound to it), and a user of https://alpha.example.com or of https://example.com/alpha goes back to the deep link they followed. They never land on a sibling organization’s address.
<a href={hostedSignInUrl(undefined, { org: organization.id })}>Sign in</a>A host per organization
An organization’s app base URL lets its people come back to it. It does not let a page on that host exchange the cookie: only an origin listed in allowedOrigins can, exactly as written. So when you give a new organization https://north.acme.com, add that origin to the auth client and release it (foir push --publish, or publish from the console). Until the release carries it, a page there cannot exchange the cookie.
If your app has a server, exchange the cookie there instead, as SSR (hosted session) describes. A server sends no browser origin, so a new organization’s host signs in as soon as the organization exists and there is nothing to list. The host still has to share the login domain’s registrable domain.
Anything else lands on the bare postLoginUrl. None of this widens credentialed access: only allowedOrigins may exchange the cookie for a token.
hostedSignInUrl is nullable, and genuinely null rather than defensively typed: the provider sets it only when hostedSession is configured, and useFoirAuth passes it through unnarrowed. Narrow it as above rather than asserting past it with ! — outside hosted-session mode there is no hosted URL to build, and you call signIn instead.
The password and OTP actions (signIn, signUp, signInWithOtp) do not apply in this mode and will throw: the user’s credential never passes through your app, which is the point.
4. Call the API
Ask for a token before each request. The SDK returns a cached one, or silently re-exchanges the cookie if it is close to expiry:
import { useFoirAuth } from '@foir/sdk/react';
function useOrders() {
const { getToken } = useFoirAuth();
return async function fetchOrders() {
const token = await getToken(); // null when signed out
const res = await fetch('https://api.foir.dev/graphql', {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-api-key': 'foir_pub_…',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ query: '{ currentUser { id email } }' }),
});
return res.json();
};
}You never handle expiry yourself: the SDK re-exchanges before the token dies, collapses concurrent callers into a single round-trip, and signs the user out only if the cookie itself is gone (a network blip does not log anyone out).
Without React
The same client is framework-agnostic:
import { createFoirSessionClient } from '@foir/sdk/auth';
const session = createFoirSessionClient({
loginOrigin: 'https://login.acme.com',
onSignOut: () => location.assign(session.signInUrl()),
});
const token = await session.getToken(); // null when signed out
const user = await session.getUser(); // { userId, email } | null
await session.signOut();More than one app on the site
The token is for one app. By default that is the app the login domain fronts. A second app of the same project on the same site (a help centre beside the shop, say) shares the person’s session and trades it for a token of its own by naming itself:
const session = createFoirSessionClient({
loginOrigin: 'https://login.acme.com',
clientId: 'acme-help',
});Foir answers only from an origin that app lists, and the token carries what the person holds of that app’s list.
Why the login domain is required
The cookie has to be first-party to your app, which means the app and the login screen must share a registrable domain (acme.com). Browsers will not send a cross-site cookie on a background request, so an SPA on myapp.vercel.app cannot hold a Foir session on api.foir.dev — the cookie would be third-party, and the session endpoint refuses credentialed cross-site calls by design.
This is the same constraint every provider in this category imposes: production cookie sessions require DNS records pointing at the provider. If you can’t add them, use the token flow and keep the access token in memory.
What’s next
- First-Party Sessions — the same idea for apps that do have a backend.
- Hosted sign-in: the full reference, with OpenID Connect discovery and verifying tokens yourself.
- How auth is billed — what a monthly active user costs against your plan.