Tutorial: Full-Stack Auth
Why start with auth
Nothing ships until people can sign in, and sign-in is the first gate every AI-built prototype hits. Sessions and their expiry, a callback flow per social provider, roles on every route — none of it is your product, all of it has a known correct shape, and getting it subtly wrong is a security incident rather than a bug.
spfn create --mode full hands you all of it already wired. This tutorial deliberately
takes the long way instead: it starts in bare mode so you see each wiring point once, and
recognize what full mode did for you.
What you'll build
A Next.js app with a real SPFN backend and working authentication:
- an admin account seeded from env at boot,
- a login page — email/password for the admin, Google social login for everyone else,
- a signed-in dashboard and an admin-only area, each page checking its visitor itself and sending a signed-out one to sign in — and back again afterwards,
with one small function every protected page calls with its own path. The finished code is
examples/03-auth — every
snippet below is taken from it, with its styling left out. The example goes on past this
tutorial, to a second factor and the page a terminal is let in from; its README walks through
them.
1. Create the project
npx spfn@beta create my-app --mode bare
cd my-app
docker compose up -d # Postgres + Redis
For a product baseline with core, auth, i18n, and the spfn ops surface already connected, use
npx spfn@beta create my-app --mode full instead — everything in sections 2 and 3 below
arrives done.
Bare mode scaffolds a Next.js app with the SPFN backend beside it (src/server/),
env files included. Check the app runs before adding auth:
pnpm spfn:dev # Next.js + SPFN API
2. Add @spfn/auth — the four wiring points
pnpm add @spfn/auth@beta
Auth wires into an SPFN app at exactly four places. Miss one and you get 401s or missing tables — check all four.
① Server lifecycle — validates auth env before the DB connects, then seeds
admin accounts and initializes RBAC once it's ready. Shortened from
src/server/server.config.ts: the doc comment and the configureAuth call that makes Battle.net
a link-only provider are left out; USER_SETTINGS is the one per-person setting the example
declares, and createAuthLifecycle() alone is enough for this tutorial:
import { Type } from '@sinclair/typebox';
import { defineServerConfig } from '@spfn/core/server';
import { createAuthLifecycle, defineUserSettings } from '@spfn/auth/server';
import { appRouter } from '@/server/router';
const USER_SETTINGS = defineUserSettings([
{
key: 'notifications.digest',
schema: Type.Union([Type.Literal('daily'), Type.Literal('weekly'), Type.Literal('off')]),
default: 'daily',
},
]);
export default defineServerConfig()
.routes(appRouter)
.lifecycle(createAuthLifecycle({ userSettings: USER_SETTINGS }))
.build();
② Router — mount the auth routes as a package and apply authentication
globally. Shortened from src/server/router.ts: its doc comments are left out. opsRouter
mounts the spfn ops surface, which Prototype to Production
covers; this tutorial needs authRouter alone:
import { defineRouter } from '@spfn/core/route';
import { authRouter, authenticate } from '@spfn/auth/server';
import { getRoot } from './routes/root';
import { getMe } from './routes/me';
import { listExamples, getExample, createExample, updateExample, deleteExample } from './routes/examples';
import { opsRouter } from './routes/ops';
export const appRouter = defineRouter({
getRoot,
getMe,
listExamples,
getExample,
createExample,
updateExample,
deleteExample,
})
.packages([authRouter, opsRouter]) // /_auth/* (authApi) + /_ops/* (spfn ops CLI)
.use([authenticate]); // global auth; public routes opt out per-route
export type AppRouter = typeof appRouter;
Two things people miss here: auth routers register through .packages([authRouter])
— not as a plain route entry — and .use([authenticate]) protects everything,
so public routes must opt out explicitly. Shortened from src/server/routes/examples.ts: the
route's input schema and its handler's body are left out:
export const listExamples = route.get('/examples')
.skip(['auth']) // public read — opt out of global authenticate
.handler(async (c) => { /* … */ });
③ RPC proxy interceptor — one side-effect import in the proxy route. Without it every
protected call 401s, because nothing signs the outbound requests. Shortened from
src/app/api/rpc/[routeName]/route.ts: its doc comment is left out, and the comment on the
first import is new:
import '@spfn/auth/nextjs/api'; // self-registers the auth interceptor — MUST come first
import { createRpcProxy } from '@spfn/core/nextjs/server';
import { eventRouteMap } from '@spfn/core/event';
import { routeMap } from '@/generated/route-map';
export const { GET, POST } = createRpcProxy({
routeMap: { ...routeMap, ...eventRouteMap },
});
No auth route map is merged: the generated routeMap carries the routes of every package
router the app router mounts with .packages(), authRouter's included. eventRouteMap is
merged by hand because it is a hand-written constant rather than a mounted router, so nothing
generates it.
④ Migrations — auth ships its tables (users, keys, roles, …) as package migrations:
pnpm spfn db migrate
3. Environment variables — which file gets what
SPFN splits env by who reads it. A key's file follows the process that needs it, not whether it is secret. This is the most common setup stumble:
| File | Read by | Holds |
|---|---|---|
.env.local |
the Next.js process (the SPFN server loads it too) | SPFN_API_URL, NEXT_PUBLIC_SPFN_APP_URL, SPFN_AUTH_SESSION_SECRET (encrypts the session cookie) |
.env.server |
SPFN server only, never Next.js | DATABASE_URL, CACHE_URL, token/encryption keys, admin seeding, OAuth credentials |
DATABASE_URL belongs in .env.server alone: the Next.js process never talks to the
database. The example ships both files as .env.local.example and
.env.server.example; its ports come from spfn.config.js (Next.js 3890, API 8890) and
its compose file maps PostgreSQL to 55432. A freshly scaffolded app uses 3790, 8790 and
5432 instead.
Minimum for this tutorial (generate real secrets with openssl rand -base64 32):
# .env.local
SPFN_API_URL=http://localhost:8890
NEXT_PUBLIC_SPFN_APP_URL=http://localhost:3890
SPFN_AUTH_SESSION_SECRET=<32+ char random secret>
# .env.server
DATABASE_URL=postgresql://spfn:spfn@localhost:55432/spfn_dev
SPFN_AUTH_VERIFICATION_TOKEN_SECRET=<32+ char random secret>
SPFN_AUTH_TOKEN_ENCRYPTION_KEYS=v1:<openssl rand -base64 32>
Seed the admin account
Add two more lines to .env.server:
SPFN_AUTH_ADMIN_EMAIL=[email protected]
SPFN_AUTH_ADMIN_PASSWORD=SecureAdmin123!
On boot, createAuthLifecycle() creates this account if it doesn't exist — you'll
see [<timestamp>] [pid=<pid>] [module=@spfn/auth:setup] [position=1] [userId=1] [role=superadmin] (INFO): Admin account created in the server log. Rules worth
knowing:
- The password must have 8+ chars with upper, lower, number, and special character.
- This simple two-var format seeds the
superadminrole and setspasswordChangeRequired: true. - For multiple accounts, explicit roles, or
passwordChangeRequired: false, use the JSON form instead:SPFN_AUTH_ADMIN_ACCOUNTS=[{"email":"…","password":"…","role":"admin","passwordChangeRequired":false}]
4. The login page
Email/password sign-in is one authApi call. The RPC interceptor from step ③
does the heavy lifting on success — generates the signing key pair and saves the
encrypted session cookie. Navigate with a full page load (not router.push) so
Server Components re-read the fresh session. Where it navigates depends on the answer: a
sign-in can need a second step, or a password change first, and the page the visitor came
from rides along as the return path. The sign-in is a press that refuses a second submit in
the submit event itself, from a ref set by the first, because a disabled button only holds once
React has drawn it, and a second submit before that would register a second key and, for an
account with a second factor, open a second challenge. The block below is
src/app/components/login-form.tsx shortened — its doc comments, the inputs' labels and the
inline styles are left out; the logic is the file's, line for line. usePress, asSubmit and
leaveFor come from src/lib/use-press.ts: copy it from the example.
'use client';
import { authApi } from '@spfn/auth';
import { InvalidCredentialsError } from '@spfn/auth/errors';
import { useState } from 'react';
import { asSubmit, leaveFor, usePress } from '@/lib/use-press';
type LoginResult = Awaited<ReturnType<typeof authApi.login.call>>;
export function LoginForm({ returnPath }: { returnPath: string })
{
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [pending, press] = usePress();
const [error, setError] = useState<string | null>(null);
async function signIn()
{
setError(null);
const result = await authApi.login.call({ body: { email, password } }).catch((error: unknown) =>
{
setError(error instanceof InvalidCredentialsError
? 'Wrong email or password (seeded admin: see .env.server).'
: 'Something went wrong. Try again.');
return null;
});
if (result)
{
await leaveFor(nextPathOf(result, returnPath));
}
}
return (
<form onSubmit={asSubmit(() => press(signIn))}>
<input type="email" required autoComplete="email" value={email} onChange={(event) => setEmail(event.target.value)} />
<input type="password" required autoComplete="current-password" value={password} onChange={(event) => setPassword(event.target.value)} />
{error && <p>{error}</p>}
<button type="submit" disabled={pending}>{pending ? 'Signing in...' : 'Sign in'}</button>
</form>
);
}
function nextPathOf(result: LoginResult, returnPath: string): string
{
if (result.mfaRequired && result.challenge)
{
return `/auth/mfa?${new URLSearchParams({ challenge: result.challenge.secret, returnUrl: returnPath })}`;
}
if (result.passwordChangeRequired || result.secondFactorEnrolmentRequired)
{
return `/account/security?${new URLSearchParams({ returnUrl: returnPath })}`;
}
return returnPath;
}
The seeded admin from section 3 takes the second branch on its first sign-in: its password
must change before its session may do anything else, and /account/security is where the
example changes it. Copy that page from the example (src/app/account/security), or seed the
tutorial's admin with the JSON form and "passwordChangeRequired": false.
The page itself is a Server Component that reads the return path and hands it to the form.
Next.js hands a repeated ?returnUrl= over as an array, which is no return path; returnPathOf
(next section) takes a string that isSafeReturnPath accepts, and the fallback otherwise.
Shortened from src/app/login/page.tsx: the doc comment, the inline styles, the sections
around the two sign-ins and the line above the social buttons are left out:
import { LoginForm } from '@/app/components/login-form';
import { OAuthLoginButtons } from '@/app/components/oauth-login-buttons';
import { returnPathOf } from '@/lib/protect-page';
export const dynamic = 'force-dynamic';
interface LoginPageProps
{
searchParams: Promise<{ returnUrl?: string | string[] }>;
}
export default async function LoginPage({ searchParams }: LoginPageProps)
{
const returnPath = returnPathOf((await searchParams).returnUrl, '/dashboard');
return (
<main>
<h1>Sign in</h1>
<LoginForm returnPath={returnPath} />
<OAuthLoginButtons returnPath={returnPath} />
</main>
);
}
It does not send a visitor who looks signed in away: getSession() only unseals the cookie,
and a cookie the backend has since refused would send the visitor back to the page that sent
them here, and round again.
Email/password registration needs the verification-code flow (
/_auth/verify-code) and a mail/SMS provider, so this tutorial registers normal users through social login instead.
5. The signed-in screen — a page that protects itself
A page checks its visitor before it renders anything, and passes its own path along so the
visitor comes back after signing in. A layout cannot do that: it is given no request path,
and it is not rendered again when the visitor moves between the pages beneath it. The check
every protected page shares is one small function. Shortened from src/lib/protect-page.ts:
the doc comments are left out, and the one on resolvesRequirements cut to a line:
import { redirect } from 'next/navigation';
import { getAuthSessionData, isSafeReturnPath } from '@spfn/auth/nextjs/server';
type Session = Exclude<Awaited<ReturnType<typeof getAuthSessionData>>, null | 'renewal-required'>;
interface ProtectOptions
{
resolvesRequirements?: boolean; // true only on the page that resolves them
}
export async function protectPage(path: string, { resolvesRequirements = false }: ProtectOptions = {}): Promise<Session>
{
const session = await getAuthSessionData();
const back = `?returnUrl=${encodeURIComponent(path)}`;
if (session === null)
{
redirect(`/login${back}`);
}
if (session === 'renewal-required')
{
redirect(`/auth/renew${back}`);
}
// Both lead to the security page, which takes the password first
if (!resolvesRequirements && (session.passwordChangeRequired || session.secondFactorEnrolmentRequired))
{
redirect(`/account/security${back}`);
}
return session;
}
export function returnPathOf(returnUrl: string | string[] | undefined, fallback: string): string
{
return typeof returnUrl === 'string' && isSafeReturnPath(returnUrl) ? returnUrl : fallback;
}
getAuthSessionData() asks the backend, so it is a live check: null is a visitor with no
readable cookie or one the backend refused; 'renewal-required' a session bound to a passkey
whose key ran out. A backend that is down throws, so the app's error page renders and nobody
is sent to sign in by an outage.
The dashboard calls it first; after it, protected API calls are safe. Shortened from
src/app/dashboard/page.tsx: the doc comment is left out, the page's markup is cut to its one
line about the visitor, and with it go the sign-out button, the connected accounts and the
links to the admin area and the home page:
import { api } from '@/lib/api-client';
import { protectPage } from '@/lib/protect-page';
export const dynamic = 'force-dynamic';
export default async function DashboardPage()
{
await protectPage('/dashboard');
const me = await api.getMe.call({}); // protected route — the page's own check came first
return <p>Signed in as {me.email ?? me.username ?? me.id} (role: <code>{me.role}</code>)</p>;
}
getMe on the server side reads the authenticated user with getAuth(c), and the linked
social accounts from socialAccountsRepository — never their tokens. Shortened from
src/server/routes/me.ts: the doc comment and the comment on connections are left out:
import { route } from '@spfn/core/route';
import { getAuth, socialAccountsRepository } from '@spfn/auth/server';
export const getMe = route.get('/me')
.handler(async (c) =>
{
const { user, userId, role, locale } = getAuth(c);
const socialAccounts = await socialAccountsRepository.findByUserId(Number(userId));
return {
id: userId,
email: user.email,
username: user.username,
role,
locale,
connections: socialAccounts.map(account => ({
provider: account.provider,
providerHandle: account.providerHandle,
})),
};
});
6. The admin area — a role the page checks itself
Same check, then the role. Shortened from src/app/admin/page.tsx: the doc comments are left
out, each answer's markup is cut to its one line, and with it goes the link to the terminal
page (/admin/terminal) and back to the dashboard:
import Link from 'next/link';
import { protectPage } from '@/lib/protect-page';
export const dynamic = 'force-dynamic';
const ADMIN_ROLES = ['admin', 'superadmin'];
export default async function AdminPage()
{
const role = (await protectPage('/admin')).role?.name;
if (!role || !ADMIN_ROLES.includes(role))
{
return <p>This area is for administrators. <Link href="/dashboard">← Dashboard</Link></p>;
}
return <p>🔐 You are here because the page's own check found one of {ADMIN_ROLES.join(', ')} (your role: {role}).</p>;
}
The match is on exact role names — superadmin does not imply admin, so list both
when either should pass (the env-seeded admin is superadmin). Signed-out visitors go to
/login?returnUrl=%2Fadmin; a signed-in visitor without the role is told the area is not for
them, rather than sent to sign in again, which would change nothing. A permission is checked
the same way, on session.permissions (each { name }).
7. Social login — Google
Create an OAuth client in the Google Cloud console (type: Web application) and register the redirect URI:
http://localhost:3890/_auth/oauth/google/callback
That URI is the default — {app origin}/_auth/oauth/google/callback — and it hits
your Next.js origin, not the API server: the scaffolded next.config.ts
rewrites /_auth/:path* to the SPFN API. Then two lines in .env.server:
SPFN_AUTH_GOOGLE_CLIENT_ID=<client id>.apps.googleusercontent.com
SPFN_AUTH_GOOGLE_CLIENT_SECRET=<client secret>
(GitHub, Kakao, Naver, and Apple are built in the same way — SPFN_AUTH_GITHUB_*,
SPFN_AUTH_KAKAO_* etc.; more providers plug in via the OAuth provider registry.)
A login button asks the backend for its provider's auth URL, carrying the return path along,
and follows it. Shortened from src/app/components/oauth-login-buttons.tsx: the block is the
function a button calls, cut out of the component; the provider list, the state startLogin
sets, the listing of configured providers and the buttons are left out:
async function startLogin(provider: DemoProvider)
{
setPending(provider);
setStatus(`Starting ${provider} login...`);
try
{
const { authUrl } = await authApi.getProviderOAuthUrl.call({
params: { provider },
body: { returnUrl: returnPath },
});
window.location.assign(authUrl);
}
catch
{
setPending(null);
setStatus(`Could not start ${provider} login. Check credentials and callback URL settings.`);
}
}
After the provider round-trip, the callback page finalizes the encrypted session
cookie — @spfn/auth/nextjs/client ships it ready-made
(src/app/auth/callback/page.tsx):
export { OAuthCallback as default } from '@spfn/auth/nextjs/client';
Social users are registered automatically on first login with the user role — so
they reach /dashboard but bounce off /admin, which is exactly the RBAC split
this tutorial is after. authApi.oauthProviders.call({}) reports which providers
are configured, letting the UI disable unconfigured buttons (the example's
OAuthLoginButtons does exactly this).
8. Run the loop
pnpm spfn:dev # or spfn:server / spfn:next in two terminals
Then walk the same loop this example was verified with:
- Open
/dashboardsigned out → the page sends you to/login?returnUrl=%2Fdashboard. - Sign in with
[email protected]/ the seeded password →/account/security, where the seeded account changes its password first (section 4); then on to/dashboard, showing your email andsuperadminrole via the protectedgetMecall. - Open
/admin→ its own check lets the seeded admin through. - Sign out (
authApi.logout) →/dashboardsends you to sign in again. - Sign in with Google →
/dashboardworks,/adminsays the area is for administrators — auser-role account in an admin-only area.
Where next
The first gate is cleared. The second one — operating the thing after it ships — is what
Prototype to Production covers, with spfn ops commands in
place of an admin dashboard.
- The SPFN pattern — the entity → route → typed client loop this app is built on.
@spfn/authreference — sessions, RBAC, invitations, OAuth providers, deletion lifecycle.examples/03-auth— the finished code, runnable as-is.