Session Drivers
@laioutr-core/frontend-coreWhat you are building
A session driver connects the storefront's user session to a login provider: an identity provider, or the customer accounts of a commerce platform. Shopify is the first driver. Build one when your project signs visitors in somewhere else.
frontend-core owns everything around the driver, so the driver stays small:
- the routes
GET /api/frontend/session,GET /api/frontend/session/loginandPOST /api/frontend/session/end; getUserSession(event)on the server anduseUserSession()in the browser;- the rules that keep a visitor's session out of shared caches;
- the presence cookie, the return to the page a login started on, the session hooks and the analytics identity.
The driver owns the provider's side: its tokens, its cookies, its login page and its logout page.
A storefront has one session, so it uses one driver. If two installed apps bring one, the storefront uses the app whose module is set up first, and the build log warns.
Scaffold the module from the App Starter.
The contract
Import the types from @laioutr-core/frontend-core/runtime, as types only. defineSessionDriver, completeLogin, endSession, markVisitorResponse, markSessionPresent and SESSION_REFRESH_LEAD_MS are server auto-imports.
import type { H3Event } from 'h3';
export interface SessionSubject {
id: string;
email?: string;
displayName?: string;
/** Flat primitives only. */
claims?: Record<string, string | number | boolean>;
}
export interface ResolvedIdentity {
/** The only part that reaches the browser. */
subject: SessionSubject;
/** Server-only. */
serverClaims?: Record<string, unknown>;
/** Server-only. When the provider's credential expires, in epoch milliseconds. */
expiresAt?: number;
}
export type LoginOutcome = { kind: 'redirect'; url: string } | { kind: 'failed'; error: Error };
export type LogoutOutcome = { kind: 'ended' } | { kind: 'redirect'; url: string };
export type EndReason = 'user' | 'expired' | 'revoked';
export interface StartLoginInput {
/** A same-origin path, already checked. */
returnTo: string;
/** The language code of the storefront domain the login started on. */
locale?: string;
/** The configured host of the storefront domain the login started on. */
host: string;
}
export interface SessionDriver {
name: string;
entry: 'redirect';
resolve(event: H3Event, options: { refresh: boolean }): Promise<ResolvedIdentity | null>;
startLogin(event: H3Event, input: StartLoginInput): Promise<LoginOutcome>;
end(event: H3Event, input: { reason: EndReason }): Promise<LogoutOutcome>;
}
entry: 'redirect' is the only kind of login today: the visitor signs in on the provider's own page.
A driver
import type { SessionDriver } from '@laioutr-core/frontend-core/runtime';
import { authorizeUrl, clearTokens, logoutUrl, readTokens, refreshTokens, writeLoginState } from '../provider';
export default defineSessionDriver({
name: '@acme/app-login',
entry: 'redirect',
async resolve(event, { refresh }) {
const tokens = readTokens(event);
if (!tokens) return null;
const due = tokens.expiresAt <= Date.now() + SESSION_REFRESH_LEAD_MS;
if (!(refresh && due)) {
if (tokens.expiresAt > Date.now()) return { subject: tokens.subject, expiresAt: tokens.expiresAt };
// Only the session route may refresh: it can still set the cookies a refresh writes.
throw new Error('the session needs a refresh to be read');
}
const fresh = await refreshTokens(event, tokens);
return fresh ? { subject: fresh.subject, expiresAt: fresh.expiresAt } : null;
},
async startLogin(event, { locale, host }) {
const state = writeLoginState(event);
return { kind: 'redirect', url: authorizeUrl({ state, locale, redirectUri: `https://${host}/api/app-login/callback` }) };
},
async end(event, { reason }) {
const tokens = readTokens(event);
clearTokens(event);
if (reason !== 'user' || !tokens?.idToken) return { kind: 'ended' };
return { kind: 'redirect', url: logoutUrl(tokens.idToken) };
},
});
resolve
- Answer
nullonly when you know that nobody is signed in. - Throw when you cannot tell: the provider did not answer, or the session needs a refresh while
refreshisfalse. The session is thenunknown, neveranonymous, so an outage does not sign anyone out. refreshistrueonly on the session route, where the response can still set the cookies a refresh writes. Every other caller reads without a refresh.- Return
expiresAt. The browser asks for the session againSESSION_REFRESH_LEAD_MS(one minute) before it. Withrefresh: true, refresh a credential that expires within that minute, so the browser is never handed one about to lapse.SESSION_REFRESH_LEAD_MSis a server auto-import. - Only
subjectreaches the browser. Put what server code needs, and the browser must not see, inserverClaims.
startLogin
frontend-core calls it from GET /api/frontend/session/login. Before the call it records the page the login started on, so your driver does not handle returnTo.
- Build your callback URL from
host, so the visitor returns to the domain they started on. - Bind the callback to this browser yourself, with a
statevalue in a short-lived cookie (login CSRF), and anoncewhere the provider issues ID tokens (replay). - Return
{ kind: 'failed', error }, or throw, when no login can start. frontend-core then sends the visitor back to their page, anduseUserSession().errorreportslogin-failed.
end
frontend-core calls it only through endSession, never directly.
- Delete your own cookies, and only those. Another app that keeps state for the session cleans it up in the
frontend-core:session:endhook. - For
reason: 'user', return a redirect to the provider's logout page when the provider's session must end too.useUserSession().logout()then sends the browser there. - Return
{ kind: 'ended' }when you cannot end the provider's session, for example when your driver no longer holds the token its logout needs. The visitor is then signed out on the storefront only, and the page reloads. Do not send the browser to a provider page that answers with an error.
The callback route
The provider sends the browser back to a route of your app. Put it under /api/app-<name>/, as Coding Standards describes.
import { exchangeCode } from '../provider';
export default defineEventHandler(async (event) => {
// This response sets one visitor's cookies, so no shared cache may store it.
markVisitorResponse(event);
try {
const identity = await exchangeCode(event, getQuery(event));
return completeLogin(event, { identity, method: 'oauth' });
} catch (error) {
return completeLogin(event, { failed: error instanceof Error ? error : new Error(String(error)) });
}
});
completeLogin establishes the session for this request, fires frontend-core:session:begin and sends the browser back to the page the login started on. On the next session answer, the browser fires frontend-core:session:signed-in once.
Give the route a rule that turns every shared cache off, so a broad isr or swr rule of the project cannot store it:
import { defu } from 'defu';
nuxt.options.routeRules = defu({ '/api/app-login/callback': { cache: false, swr: false, isr: false } }, nuxt.options.routeRules);
Ending a dead session
Every path of your app that finds the provider's session dead calls endSession: the provider refused a refresh, or rejected a token.
await endSession(event, { reason: 'expired', subject });
endSession fires frontend-core:session:end, calls your end, removes the presence cookie and leaves the request anonymous. On a response that a shared cache may store, it only warns, and the next request of that visitor ends the session.
Registering the driver
import type {} from '@laioutr-core/frontend-core';
import { createResolver, defineNuxtModule } from '@nuxt/kit';
export default defineNuxtModule({
setup(options, nuxt) {
const { resolve } = createResolver(import.meta.url);
nuxt.hook('laioutr:session-driver:register', ({ drivers }) => {
drivers.push({
name: '@acme/app-login',
path: resolve('./runtime/server/session/driver'),
accountUrl: 'https://login.acme.example/account',
});
});
},
});
nameis your package name. The session reports it as the driver.accountUrlis optional. It becomesuseUserSession().accountHref, so it must be the same for every visitor.- The type import makes the hook known to TypeScript.
Sessions from before your driver
The browser asks for the session only when the laioutr_session_hint cookie is present. A visitor who signed in before your app became a driver has no such cookie. When your app finds such a session on a visitor request, call markSessionPresent(event). From the next page load on, the visitor is signed in.