Skip to content

Fastify integration

@flowcatalyst/sdk/fastify is a Fastify 5 plugin that signs users in with FlowCatalyst and authenticates API callers, and gives route code one request.principal for both. It is the backend half of Sign in users and OIDC login for a Node.js app.

  • Browsers get the OIDC authorization-code flow with PKCE, ending in an encrypted session cookie.
  • API callers send Authorization: Bearer <access token>; the plugin verifies it against the platform’s keys.
  • Roles come from the FlowCatalyst token. Permissions are resolved locally from a catalogue you declare in code. See Tokens and Permissions and roles.

Install the optional peers you need: pnpm add fastify @fastify/cookie jose.

Register a confidential web client in the console with redirect URI https://your-app.example.com/auth/callback, then:

import Fastify from 'fastify';
import { flowcatalystAuth, defineRbac, generateSessionSecret } from '@flowcatalyst/sdk/fastify';
const rbac = defineRbac()
.role('shop:admin').grants('shop:*')
.role('shop:viewer').grants('shop:read')
.role('support').grants('ticket:*')
.build();
const app = Fastify();
await app.register(flowcatalystAuth, {
baseUrl: 'https://platform.example.com',
clientId: process.env.FC_CLIENT_ID!,
clientSecret: process.env.FC_CLIENT_SECRET!,
cookie: { secret: process.env.SESSION_SECRET! }, // 32 bytes, base64url, base64 or hex
rbac,
});
app.get('/dashboard', { preHandler: app.fc.requireSession() }, async (req) => ({
hello: req.principal!.name,
}));
app.post('/api/orders', { preHandler: app.fc.requireBearer() }, async (req, reply) => {
if (!req.principal!.hasPermissionTo(['shop:write'])) return reply.code(403).send();
// ...
});
app.get('/api/me', { preHandler: app.fc.requireAuth() }, async (req) => ({
id: req.principal!.id,
roles: req.principal!.roles,
}));

Generate a session secret once and keep it in your secret store: generateSessionSecret() returns a fresh 32-byte base64url string.

Required: baseUrl, clientId, clientSecret, cookie.secret.

Option Default Meaning
scope openid profile email OIDC scopes requested.
expectedAudience flowcatalyst Expected aud of Bearer access tokens.
rbac none Local role-to-permission catalogue. Without it, permission checks always fail.
portal false Sign in through the portal identity plane. See Portal.
client none Client identifier slug whose login branding the sign-in pages wear. A ?client= on the login route overrides it. Cosmetic only; it does not change who may sign in. Ignored in portal mode.
cookie.name fc_session Session cookie name.
cookie.secret required One secret, or an array for rotation (the first encrypts, all decrypt).
cookie.path, domain /, unset Cookie scope.
cookie.httpOnly true
cookie.secure true Set false for local http development, or the cookie is never sent back.
cookie.sameSite lax
cookie.maxAge 8 hours (seconds) Also the session lifetime.
sessionStore cookie store A SessionStore; see Session storage.
routes /auth/login, /auth/callback, /auth/logout Override the three routes the plugin adds.
returnToQueryParam returnTo Query parameter that carries the post-login destination.
publicBaseUrl derived from the request Public origin used to build the callback URL. Set it behind a proxy you do not control; otherwise the plugin uses x-forwarded-proto and x-forwarded-host.

On every request an onRequest hook resolves a principal:

  1. If an Authorization: Bearer header is present, the token is verified (signature against the platform’s JWKS, issuer, audience, expiry). A valid token sets request.principal; an invalid one leaves it unset. A Bearer header is never downgraded to a cookie.
  2. Otherwise the session store is read. When the access token is within 60 seconds of expiry and a refresh token exists, the plugin refreshes it and rewrites the session; if the refresh fails the session is cleared.
  3. A principal already set by an earlier plane is never overwritten (see Two planes in one app).

A token that carries token_use other than api or identity (for example a field-worker token) is refused as a platform principal whatever its audience.

The plugin adds three routes:

Route Behaviour
GET /auth/login Starts the authorization-code flow with PKCE, storing state in a short-lived encrypted cookie, and redirects to the platform. ?returnTo=/path is accepted only if it is a same-origin path.
GET /auth/callback Checks state, exchanges the code, verifies the ID token, writes the session and redirects to returnTo. A bad state answers 400 { "error": "invalid_oauth_state" }.
POST /auth/logout Clears the session and answers 204, or redirects to redirectTo from the JSON body.

The session’s identity comes from the verified ID token, which proves who signed in; authority lists (tier, clients, applications, roles) are merged from it. See Tokens and claims.

app.fc provides three preHandler factories:

Guard Accepts When nothing valid is present
requireSession() session cookie Browser navigation (GET or HEAD with Accept: text/html): 302 to /auth/login?returnTo=…. Anything else: 401.
requireBearer() Bearer token 401 { "error": "unauthorized" } with WWW-Authenticate: Bearer realm="flowcatalyst".
requireAuth() either Same negotiation as requireSession.

Redirecting only real navigations matters: a fetch from a single-page app would otherwise follow a 302 chain to the platform’s authorize URL and fail on CORS. The platform’s API sends no CORS headers, so the app that hosts the SPA should serve the API on the same origin. Only two groups of platform endpoints answer cross-origin, for the origins on the console’s CORS Origins list: the push gateway (/api/push/*) and the field-worker device protocol (/field/*, for a web page that uses the browser build of the field library). See CORS.

request.principal has the same shape for cookie and Bearer callers:

Field or method Meaning
id, type Principal id (prn_… for a user, a service principal id otherwise); USER or SERVICE.
name, email
scope anchor, partner or client: the tenancy tier.
clients Raw claim: "{id}:{code}" pairs, or ["*"] for an anchor.
clientIds, clientCodes Parsed halves of clients, aligned by position.
roles Role names from the token, such as shop:admin.
applications, applicationCodes, allApplications Application ids, their codes, and whether the principal reaches every application.
portal Present only for a portal login: clientId and, for an app-linked portal client, appCode and appId.
mechanism session or bearer.
sessionData Your own bag, stored with the session. Empty for Bearer.
hasRole(r), hasRoles(rs), hasAnyRole(rs) Role checks (hasRoles means all).
hasPermissionTo(ps), hasAnyPermissionTo(ps) Permission checks against the catalogue (all, any).
isAnchor() Anchor tier, or * in clients.
canAccessClient(idOrCode) Anchor, or the id or code is in the principal’s clients.

FlowCatalyst tokens carry roles. What a role may do in your application is your code’s business, so you declare it:

const rbac = defineRbac()
.role('billing-admin').grants('invoice:create', 'invoice:read')
.role('billing-viewer').grants('invoice:read')
.role('support').grants('ticket:*')
.build();

A principal’s permissions are the union over its roles. Wildcards are suffix-only on : boundaries: ticket:* matches ticket:close, * matches everything, and ticket:r* matches nothing. Unknown roles grant nothing. A role may be declared bare (bidder) or qualified (shop:bidder); the catalogue matches the claim in either form, except where two declarations share a bare name, which then match exactly only.

The plugin has no hook of its own. Add an ordinary preHandler after registering it:

app.addHook('preHandler', async (req) => {
if (!req.principal) return;
const user = await db.users.upsert(req.principal.id, req.principal.email);
req.principal.sessionData.localUserId = user.id;
});

Changes to sessionData made this way are not persisted: the session is read from the store on each request. Use a server-side store and write to it yourself if you need mutable per-session state.

The default is local: clear the cookie. To end the platform’s session as well, redirect to its logout page:

app.post('/auth/logout-and-redirect', async (req, reply) => {
await app.fc.logout(req, reply, { redirectTo: 'https://platform.example.com/logout' });
});

The default CookieSessionStore holds the whole encrypted session in the cookie (AES-GCM, key from cookie.secret), so it needs no infrastructure but is limited to about 4 KB. For more data, or to revoke sessions server-side, use a store that keeps the payload and puts only an opaque id in the cookie:

import pg from 'pg';
import { PgSessionStore, initSessionSchema } from '@flowcatalyst/sdk/fastify';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
await initSessionSchema(pool);
await app.register(flowcatalystAuth, {
// ...
sessionStore: new PgSessionStore({
executor: pool,
cookieName: 'fc_session',
cookieOptions: { path: '/', httpOnly: true, secure: true, sameSite: 'lax', maxAge: 60 * 60 * 8 },
}),
});
Store Options
PgSessionStore executor (a node-postgres-compatible pool or client), cookieName, cookieOptions, table (default fc_sessions), reapIntervalMs (default hourly; false disables the sweep of expired rows).
RedisSessionStore client (ioredis-compatible), cookieName, cookieOptions, prefix (default fc:session).
CookieSessionStore cookieName, secret, cookieOptions.

PgSessionStore issues a new session id on every write, including the plugin’s mid-session token refresh, and deletes the row it replaces in the same round trip. The plugin starts the expired-row sweep when the store is registered and stops it when Fastify closes. Reads already ignore expired rows, so the sweep affects table growth only. initSessionSchema(pool) runs CREATE_SESSION_TABLE_SQL, both exported.

An application can register the plugin twice, for example an encapsulated customer-portal plane and a root-context management plane, each with its own cookie name and routes. The first plane that authenticates a request wins: a later plane’s hook does not overwrite an existing request.principal. Without that rule, an administrator holding both cookies would have had their management session override the portal principal on portal routes. Give each registration a distinct cookie.name and distinct routes.

The plugin answers with HTTP statuses rather than throwing: 302 or 401 from guards, 400 invalid_oauth_state from the callback. Token verification failures leave request.principal unset, so a guard answers 401. A failed OIDC discovery is retried on the next request rather than cached.

The SDK’s own tests start the plugin against an in-process mock OIDC issuer and drive the whole dance with fetch: the login redirect, the callback, the session cookie, Bearer verification, the 302 versus 401 negotiation and logout. Use the same approach in your tests: boot Fastify with cookie: { secret, secure: false }, point baseUrl at a mock issuer that serves discovery, JWKS and a token endpoint, and call app.inject or fetch. For route logic that only reads the principal, decorate request.principal in a test onRequest hook and skip the OIDC flow.

A runnable example against a local fcdev is in clients/typescript-sdk/examples/fastify-app.