React & Next.js
Foir ships the client layer so you don’t hand-roll it. @foir/sdk/react gives
you a provider, hooks, and drop-in components; @foir/sdk/next handles
server-side sessions and route protection for the Next.js App Router. Both are
built on @foir/sdk/auth, so you can drop down to the raw flows any time.
Note: These are entry points of the
@foir/sdkpackage —@foir/sdk/reactneedsreact, and@foir/sdk/nexttargets the Next.js App Router. You’ll also need a project, a registered auth client, and a publishable API key — see the Quickstart.
React
Wrap your app in FoirProvider, then read the session with hooks or drop in the
components. The default session store is the browser’s localStorage; pass your
own adapter for a cookie store.
Note:
localStorageis the simplest option, not the safest one — a token inlocalStorageis readable by any script on the page. If you have a backend, use the Next.js adapter below. If you don’t, but you can add a custom login domain, passhostedSessioninstead ofadapterand the tokens never touch JavaScript at all.
'use client';
import { FoirProvider, SignIn, UserButton, useFoirSession } from '@foir/sdk/react';
const env = {
PLATFORM_API_URL: process.env.NEXT_PUBLIC_PLATFORM_API_URL,
PLATFORM_API_KEY: process.env.NEXT_PUBLIC_PLATFORM_API_KEY, // a publishable key
};
export function App() {
return (
<FoirProvider env={env}>
<Header />
<SignIn afterSignInUrl="/dashboard" />
</FoirProvider>
);
}
function Header() {
const { isAuthenticated, isLoading } = useFoirSession();
if (isLoading) return null;
return isAuthenticated ? <UserButton afterSignOutUrl="/" /> : null;
}<FoirProvider>hydrates the stored session on mount and provides it to the tree.useFoirSession()returns{ status, user, isAuthenticated, isLoading };useFoirUser()returns the user ({ id, email }) or null.<SignIn>renders an email/password (or OTP) form plus OAuth buttons, or a hosted-redirect button when you passhostedUrl.<OAuthButtons>discovers the project’s providers and starts the redirect flow;<UserButton>shows the email and a sign-out button.
For a fully custom UI, drive it with useFoirAuth(): signIn, signUp,
signInWithOtp, requestOtp, signInWithProvider, finishProviderSignIn,
signOut, getToken. signUp signs nobody in: it mails the address a code,
and signInWithOtp with that code finishes the account and the session.
signOut ends the sign-in on the platform as well as in the browser.
The components are unstyled by default (they carry data-foir-* attributes and
accept a className), so you own the look.
Next.js (App Router)
For a server-rendered app, @foir/sdk/next keeps the tokens in HttpOnly
cookies: the session your own server holds, from First-Party Sessions,
without the boilerplate.
Protect routes with the middleware:
// middleware.ts
import { createFoirMiddleware } from '@foir/sdk/next';
export const middleware = createFoirMiddleware({ signInUrl: '/sign-in' });
export const config = { matcher: ['/dashboard/:path*'] };Read the session in a server component:
// app/dashboard/page.tsx
import { cookies } from 'next/headers';
import { getFoirSession } from '@foir/sdk/next';
export default async function Dashboard() {
const user = await getFoirSession(await cookies());
if (!user) return null; // middleware already redirected
return <p>Signed in as {user.email}</p>;
}Sign in from a route handler (the tokens are written to HttpOnly cookies):
// app/sign-in/route.ts
import { cookies } from 'next/headers';
import { foirSignInWithPassword, type FoirEnv } from '@foir/sdk/next';
// Server-side only — NOT the NEXT_PUBLIC_ pair. This route runs on the server
// and the key never reaches the browser.
const env: FoirEnv = {
PLATFORM_API_URL: process.env.PLATFORM_API_URL,
PLATFORM_API_KEY: process.env.PLATFORM_API_KEY,
};
export async function POST(req: Request) {
const { email, password } = await req.json();
await foirSignInWithPassword({ env, store: await cookies(), email, password });
return Response.json({ ok: true });
}env is required, not optional — every server helper takes it.
Other server helpers: foirSignInWithOtp, foirSignUpWithPassword (which
mails a code, finished with foirSignInWithOtp), startFoirProviderSignIn
(where to send the browser, keeping the step its finish comes back to),
finishFoirProviderSignIn (bring an OAuth callback’s code/state back to it),
getFoirToken, and foirSignOut. They all take the same env object, so it is
worth putting in a shared module rather than rebuilding it in each route.
Note: The middleware only checks for the session cookie’s presence — it’s edge-safe and fast. The access token itself is validated by the Foir API when you call it, so keep the real gate in your route handlers and server components via
getFoirSession.
Showing a user what their role allows
Some of your users are staff: they see a manager menu, an edit button, a wholesale price list. Ask Foir which roles the signed-in user holds, and what those roles let them do, and show the page to match.
In React, useFoirAccess() reads both:
'use client';
import { useFoirAccess } from '@foir/sdk/react';
function Toolbar() {
const { isLoading, hasRole, hasScope } = useFoirAccess();
if (isLoading) return null;
return (
<nav>
{hasRole('staff') && <a href="/back-office">Back office</a>}
{hasScope('records:write:post') && <button>Edit post</button>}
</nav>
);
}hasRole(key)is true when the user holds the role with that key, across the project or in the organization they are in.hasScope(scope)is true when what they may do covers that scope. It reads scopes the way Foir does:records:writecoversrecords:write:post,records:read.allcoversrecords:read, and never the other way round.statusisloadinguntil Foir has answered, thenready. It isunavailablewhen Foir could not be asked, and then both answer false: nothing is offered on an answer that was not given.reload()asks again. The hook also asks again whenever the session refreshes, so a role you take away disappears from the page without a new sign-in.
The first component to call the hook makes one request, and every other component shares its answer. A page that never calls it makes none.
On the server, the same answers come from @foir/sdk/auth. requireRole is the
guard for a route that only staff may open:
// app/back-office/orders/route.ts
import { cookies } from 'next/headers';
import { createFoirCookieAdapter } from '@foir/sdk/next';
import { requireRole, FoirAccessDeniedError } from '@foir/sdk/auth';
export async function GET() {
try {
await requireRole(createFoirCookieAdapter(await cookies()), env, 'staff');
} catch (err) {
if (err instanceof FoirAccessDeniedError) {
// err.reason: 'signed_out' | 'role_not_held' | 'roles_unknown'
return new Response(null, { status: err.reason === 'signed_out' ? 401 : 403 });
}
throw err;
}
// ...
}requireScope(adapter, env, scope) is the same guard for a scope.
getSessionAccess(adapter, env) returns the access without refusing, as plain
data you can pass to the browser and read there with hasRole(access, key) and
hasScope(access, scope).
In a Server Component, where cookies cannot be written, read with the token instead:
// app/back-office/page.tsx
import { cookies } from 'next/headers';
import { getFoirToken } from '@foir/sdk/next';
import { userAccess, hasRole } from '@foir/sdk/auth';
export default async function BackOffice() {
const token = await getFoirToken(await cookies());
const access = token ? await userAccess(env, { bearerToken: token }) : null;
if (!hasRole(access, 'staff')) return <p>This page is for staff.</p>;
// ...
}Nothing is remembered between calls. Each one asks Foir, so a role given or taken away is seen by the next request.
Note: These decide what a page shows. They protect nothing. Foir checks every read and every write itself, whatever your page offers, so a user who is not staff is refused by the API even if they reach the button. Hide the control because it would not work for them, not to keep them out.
Going lower
Both packages sit on @foir/sdk/auth, the framework-agnostic layer —
password, sign-up, OTP and provider sign-in, each keeping its session in a
SessionAdapter. Reach for it directly when you’re not on React
or Next, or when you want full control of the session store. See
User Authentication for the underlying flows and
the token model.