server.ts
From the guide Fastify authentication in TypeScript with Supabase: a full example. Placeholder values only: put your own keys in environment variables, never in the code.
// server.ts: the app. Registers the session plugin, the sign-in routes and one protected route.
// The app is built by a function, so a test can pass a fake provider and database.
import Fastify from 'fastify';
import { sessionPlugin } from './session-plugin.ts';
import { authRoutes, type OAuthProvider } from './auth-routes.ts';
import { createDb } from './db.ts';
export function buildApp(deps: { provider: OAuthProvider; db?: ReturnType<typeof createDb>; appOrigin?: string }) {
const app = Fastify({ logger: true });
const db = deps.db ?? createDb();
app.register(sessionPlugin, { appOrigin: deps.appOrigin ?? process.env.APP_ORIGIN ?? '' });
app.register(authRoutes, { db, provider: deps.provider });
// A route that needs a signed-in person. Scope every query to request.session.userId yourself:
// the secret key bypasses Row Level Security.
app.register(async (protectedRoutes) => {
protectedRoutes.addHook('preHandler', protectedRoutes.requireSession);
protectedRoutes.get('/api/me', async (request) => ({ userId: request.session!.userId }));
});
return app;
}