Fastify authentication in TypeScript with Supabase: a full example

Add sign-in to a Fastify app in TypeScript: a session plugin, OAuth routes, protected routes with preHandler, and Supabase on the server. Copy-ready, tested code.

Illustration: a request with its cookie passes the onRequest and preHandler hooks, then its handler reaches a locked database.

To add authentication to a Fastify app, read the session cookie in an onRequest hook, put the user on request.session, and protect routes with a preHandler that stops the request when nobody is signed in. This guide builds that in TypeScript with Supabase as the database: a session plugin, the OAuth sign-in routes and a protected route, all ready to copy.

It is the Fastify version of our guide to Supabase authentication in TypeScript, which explains the two safe ways to do it, which Supabase key goes where, and how to lock your tables. Read that first if you are new to Supabase’s keys: this post only adds the Fastify parts.

Before you start

  • The general guide’s files. Three files from it have no framework in them and work unchanged here: session.ts (the signed session cookie), oauth-state.ts (the OAuth state and PKCE checks) and db.ts (the database calls with the secret key). Copy them from that guide, or open them on their own: session.ts, oauth-state.ts, db.ts. Its tables.sql creates and locks the users table, and its env.example lists the environment variables.
  • Node.js 22.18 or later, and TypeScript. From 22.18 Node.js runs .ts files directly. Every file below typechecks in strict mode with TypeScript 7.0.2 and the tsconfig.json of the general guide, which you can use as it is.
  • An OAuth app at the service your users sign in with, with its redirect URI set to https://app.example.com/api/auth/callback (your domain).
  • Packages. The code was checked against these versions:
install.shShellRawExternal
npm install fastify@5.12.8 @fastify/cookie@11.1.5 fastify-plugin@6.0.1
npm install -D typescript@7.0.2 @types/node@26.6.6

How a request goes through the app

Four steps. onRequest reads the session cookie and puts the user on request.session. preHandler runs requireSession: a POST from another site gets 403, no session gets 401. The handler scopes its query to the user. Supabase is called from the server only, with the secret key.
Each request, from the cookie to the database.

Fastify runs its hooks in a fixed order: onRequest first, then the body is parsed and validated, then preHandler, then your route. Reading the session in onRequest means every route can see who is signed in. Refusing requests in preHandler means only the routes that ask for it are protected, and when a hook replies, Fastify stops there: the route handler never runs.

Step 1: read the session once, in an onRequest hook

session-plugin.tsTypeScriptRawExternal
// session-plugin.ts: reads the signed session cookie on every request and puts the user on request.session.
// Wrapped in fastify-plugin, so the decorator and the hook apply to every route of the app, not only inside this plugin.
// session.ts is the framework-free file from the general guide (signSession, verifySession).
import fp from 'fastify-plugin';
import cookie from '@fastify/cookie';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { verifySession, SESSION_COOKIE, type Session } from './session.ts';

declare module 'fastify' {
  interface FastifyRequest {
    /** The signed-in user, or null. Set by the onRequest hook below. */
    session: Session | null;
  }
}

export interface SessionPluginOptions {
  /** Your site's origin, e.g. https://app.example.com: any method other than GET and HEAD must come from it. */
  appOrigin: string;
}

export const sessionPlugin = fp<SessionPluginOptions>(async (app, opts) => {
  // An empty origin would make every sign-out fail with 403 and hide the missing APP_ORIGIN: stop at start-up.
  if (!opts.appOrigin) throw new Error('appOrigin is required');
  // Another plugin of the app may have registered @fastify/cookie already, and registering it twice is an error.
  if (!app.hasRequestDecorator('cookies')) await app.register(cookie);
  // Fastify asks for null as the starting value of an object decorator, then a value per request in onRequest.
  app.decorateRequest('session', null);
  app.addHook('onRequest', async (request) => {
    request.session = verifySession(request.cookies[SESSION_COOKIE], Date.now());
  });

  /** preHandler for routes that need a signed-in person. The Origin is checked first. */
  app.decorate('requireSession', async (request: FastifyRequest, reply: FastifyReply) => {
    const mutating = request.method !== 'GET' && request.method !== 'HEAD';
    if (mutating && request.headers.origin !== opts.appOrigin) return reply.code(403).send({ error: 'bad_origin' });
    if (!request.session) return reply.code(401).send({ error: 'not_signed_in' });
  });
});

declare module 'fastify' {
  interface FastifyInstance {
    requireSession: (request: FastifyRequest, reply: FastifyReply) => Promise<FastifyReply | undefined>;
  }
}
  • declare module 'fastify' adds session to Fastify’s FastifyRequest type, so request.session is typed in every route (Fastify’s TypeScript reference shows the pattern).
  • Fastify asks for null as the starting value of a request decorator that holds an object, then a fresh value per request in onRequest. That is what decorateRequest('session', null) and the hook do.
  • requireSession checks the Origin before the session on any method other than GET and HEAD, so a request from another site learns nothing about who is signed in.
  • The plugin stops the app at start-up when appOrigin is empty: an empty value would refuse every sign-out and hide the missing APP_ORIGIN.
  • It registers @fastify/cookie only when no other plugin has: registering it twice is an error, and the Supabase Auth plugin below needs the same cookies.

Wrap the session plugin in fastify-plugin

Fastify keeps each plugin’s decorators and hooks inside that plugin: a route registered elsewhere doesn’t see them. Wrapping the session plugin in fp() lifts that wall for this one plugin, so request.session and app.requireSession exist everywhere. The protected routes in step 3 do the opposite on purpose: their preHandler stays inside their own plugin, so it can’t lock your public routes by accident.

Two lists. Wrapped in fastify-plugin, for the whole app: request.session, the onRequest hook that fills it, app.requireSession. A plain register, for its own routes only: the preHandler of the protected routes, any decorator added inside it.
What reaches the whole app, and what stays inside its plugin.

Step 2: add routes to start, finish and end a sign-in

auth-routes.tsTypeScriptRawExternal
// auth-routes.ts: sign in with an OAuth provider, keep the person in a signed cookie, sign out. Fastify version.
// oauth-state.ts, session.ts and db.ts are the framework-free files from the general guide.
import type { FastifyPluginAsync } from 'fastify';
import type { Db } from './db.ts';
import { newNonce, newVerifier, challengeOf, signState, verifyState, STATE_COOKIE, VERIFIER_COOKIE, STATE_TTL_MS } from './oauth-state.ts';
import { signSession, SESSION_COOKIE, SESSION_TTL_MS } from './session.ts';

/** What the routes need from the provider: its consent page, and the person behind a code. */
export interface OAuthProvider {
  name: string;
  /** The provider's consent page URL, with your client id, redirect URI, scopes and this state. Add code_challenge=<codeChallenge> and code_challenge_method=S256 (PKCE). */
  authorizeUrl(state: string, codeChallenge: string): string;
  /** Exchanges the code for a token, then reads who signed in. Send code_verifier=<codeVerifier> in the token request. */
  identify(code: string, codeVerifier: string): Promise<{ providerUserId: string; email: string | null }>;
}

export interface AuthRoutesOptions {
  db: Pick<Db, 'upsertUser'>;
  provider: OAuthProvider;
}

// HttpOnly: no script can read it. Secure: HTTPS only. SameSite=Lax: not sent on a cross-site POST.
// @fastify/cookie takes maxAge in seconds.
const base = { httpOnly: true, secure: true, sameSite: 'lax' } as const;
const signInCookie = { ...base, path: '/api/auth', maxAge: STATE_TTL_MS / 1000 }; // the state nonce and the PKCE verifier
const sessionCookie = { ...base, path: '/', maxAge: SESSION_TTL_MS / 1000 };
// A cookie with the __Host- prefix is cleared only by a Set-Cookie that is also Secure with Path=/.
const clearOptions = (path: string) => ({ ...base, path });

export const authRoutes: FastifyPluginAsync<AuthRoutesOptions> = async (app, { db, provider }) => {
  // To the provider's consent page, with a signed state and PKCE challenge; their secrets go in cookies.
  app.get('/api/auth/start', async (_request, reply) => {
    const nonce = newNonce();
    const verifier = newVerifier();
    reply.setCookie(STATE_COOKIE, nonce, signInCookie);
    reply.setCookie(VERIFIER_COOKIE, verifier, signInCookie);
    const url = provider.authorizeUrl(signState(nonce, Date.now() + STATE_TTL_MS), challengeOf(verifier));
    return reply.header('cache-control', 'no-store').redirect(url);
  });

  // Back from the provider: check the state and the verifier against their cookies, find or create the user, set the session cookie.
  // The schema makes Fastify answer 400 when a value is repeated, so the handler never gets an array.
  app.get<{ Querystring: { code?: string; state?: string; error?: string } }>(
    '/api/auth/callback',
    { schema: { querystring: { type: 'object', properties: { code: { type: 'string' }, state: { type: 'string' }, error: { type: 'string' } } } } },
    async (request, reply) => {
      reply.header('cache-control', 'no-store');
      // Every way out clears both cookies: each sign-in attempt gets one try.
      reply.clearCookie(STATE_COOKIE, clearOptions('/api/auth'));
      reply.clearCookie(VERIFIER_COOKIE, clearOptions('/api/auth'));
      const { code, state, error } = request.query;
      if (error) return reply.redirect('/?error=denied'); // the person said no on the provider's page
      const nonce = verifyState(state, Date.now());
      const verifier = request.cookies[VERIFIER_COOKIE];
      if (!nonce || nonce !== request.cookies[STATE_COOKIE] || !code || !verifier) return reply.redirect('/?error=bad_state');
      try {
        const who = await provider.identify(code, verifier);
        const userId = await db.upsertUser({ provider: provider.name, providerUserId: who.providerUserId, email: who.email });
        reply.setCookie(SESSION_COOKIE, signSession({ userId, expiresAt: Date.now() + SESSION_TTL_MS }), sessionCookie);
        return reply.redirect('/app');
      } catch (err) {
        request.log.error({ err }, 'sign-in failed'); // your log only; the visitor gets a short code
        return reply.redirect('/?error=signin_failed');
      }
    },
  );

  // Sign out: POST from your own site only (requireSession checks the Origin). The cookie was the session.
  app.post('/api/auth/logout', { preHandler: app.requireSession }, async (_request, reply) => {
    reply.header('cache-control', 'no-store');
    reply.clearCookie(SESSION_COOKIE, clearOptions('/'));
    return reply.code(204).send();
  });
};
  • authorizeUrl and identify are yours to write for your provider. Step 5 of the general guide says what each one must do, including the PKCE challenge and verifier.
  • @fastify/cookie sets and reads the cookies. Its maxAge is in seconds, so the milliseconds from session.ts are divided by 1,000. The flags and the __Host- name are explained in step 4 of the general guide.
  • A __Host- cookie is cleared only by a Set-Cookie that is also Secure with Path=/, so clearCookie gets the same flags.
  • The start route sets two cookies, the state’s nonce and the PKCE verifier. The callback needs both, and clears both first, whatever happens next: each sign-in attempt gets one try.
  • The start, callback and sign-out routes answer with cache-control: no-store, so no cache keeps a response that sets or clears a cookie.
  • The querystring schema makes Fastify answer 400 when code, state or error is repeated (?code=a&code=b), so the handler never gets an array.
  • Errors go to Fastify’s logger with request.log.error. The visitor only sees a short code such as signin_failed.

Step 3: protect routes with a scoped preHandler

server.tsTypeScriptRawExternal
// 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;
}
Four rows. session.ts, oauth-state.ts and db.ts come from the general guide, with no framework in them. session-plugin.ts reads the cookie on every request and adds app.requireSession. auth-routes.ts has the start, callback and sign-out routes. server.ts puts it together with one protected route.
The files of the app, and what each one does.

buildApp takes the provider and the database as arguments, so a test can pass fakes and call the routes with Fastify’s app.inject(), without a network or a real Supabase project. That is how the code on this page was tested.

Step 4: start the server on 127.0.0.1

Write a provider.ts that exports myProvider, an object that follows the OAuthProvider interface of step 2. Then add main.ts, which builds the app and listens:

main.tsTypeScriptRawExternal
// main.ts: starts the server. Run it with: node --env-file=.env main.ts
// package.json needs "type": "module": this file uses a top-level await.
import { buildApp } from './server.ts';
import { myProvider } from './provider.ts'; // your OAuthProvider: see the general guide, step 5
const app = buildApp({ provider: myProvider });
// 127.0.0.1 keeps the server on this machine. In a container, use host '0.0.0.0' so the container can reach it.
await app.listen({ port: 3000, host: '127.0.0.1' });

Put your values in .env (the names are in env.example) and run node --env-file=.env main.ts. Fastify’s Getting Started guide notes that its examples listen on 127.0.0.1 only, which keeps the server on your machine. In a container, use host: '0.0.0.0' so the container can reach it.

The other way: Supabase Auth in Fastify

If you’d rather have Supabase keep your users (the second way in the general guide), the browser signs in with Supabase Auth, and your Fastify server reads the session from Supabase’s cookies with @supabase/ssr:

supabase-auth-fastify.tsTypeScriptRawExternal
// supabase-auth-fastify.ts: the other way, with Supabase Auth holding your users. A Fastify plugin.
// npm install @supabase/supabase-js@2.119.2 @supabase/ssr@0.12.7 @fastify/cookie@11.1.5 fastify-plugin@6.0.1
// It uses the PUBLISHABLE key (sb_publishable_...): RLS policies decide what each user may touch.
import fp from 'fastify-plugin';
import cookie from '@fastify/cookie';
import { createServerClient } from '@supabase/ssr';
import type { FastifyReply, FastifyRequest } from 'fastify';

declare module 'fastify' {
  interface FastifyRequest {
    /** The signed-in Supabase user's id, or null. */
    userId: string | null;
  }
}

/** A Supabase client for one request: it reads the session cookies and writes refreshed ones on the reply. */
export function supabaseFor(request: FastifyRequest, reply: FastifyReply) {
  return createServerClient(process.env.SUPABASE_URL!, process.env.SUPABASE_PUBLISHABLE_KEY!, {
    cookies: {
      getAll() {
        return Object.entries(request.cookies).map(([name, value]) => ({ name, value: value ?? '' }));
      },
      setAll(cookiesToSet, headers) {
        for (const { name, value, options } of cookiesToSet) reply.setCookie(name, value, options);
        // Cache headers from Supabase, so a CDN never stores a response that sets someone's session cookie.
        for (const [key, value] of Object.entries(headers)) reply.header(key, value);
      },
    },
  });
}

export const supabaseAuthPlugin = fp(async (app) => {
  // Registering @fastify/cookie twice is an error, and the session plugin of the first way may have done it already.
  if (!app.hasRequestDecorator('cookies')) await app.register(cookie);
  app.decorateRequest('userId', null);
  app.addHook('onRequest', async (request, reply) => {
    // getClaims() checks the token's signature, so it is safe to trust on the server. Never trust getSession() here.
    const { data, error } = await supabaseFor(request, reply).auth.getClaims();
    request.userId = error || !data ? null : data.claims.sub;
  });
});
  • It uses the publishable key, not the secret one: with Supabase Auth, Row Level Security policies decide what each user may touch. The general guide has the policies to add.
  • getClaims() is the call to trust on the server, and getSession() is not (see why in the general guide).
  • setAll writes refreshed session cookies with reply.setCookie, and the cache headers Supabase passes with them, so a CDN never stores a response that sets someone’s session.
  • Like the session plugin, it registers @fastify/cookie only when no other plugin has, so both plugins can live in one app.

Install @supabase/supabase-js@2.119.2 and @supabase/ssr@0.12.7 for this file; it typechecks against those versions.

How this code is tested

Every file on this page typechecks in strict mode against Fastify 5.12.8, @fastify/cookie 11.1.5, fastify-plugin 6.0.1, @supabase/ssr 0.12.7 and @supabase/supabase-js 2.119.2. The sign-in code was also run with app.inject():

  • /api/auth/start redirects with a signed state and an S256 challenge, and puts the state’s nonce and the verifier in two HttpOnly cookies that last 10 minutes.
  • The callback signs the user in when the state matches its cookie, trades the code with the verifier, and clears both cookies. It refuses a state from another browser and a callback without its verifier cookie, and answers 400 to a repeated code.
  • /api/me answers 401 without a session, and the user’s id with one.
  • Sign-out refuses a POST from another site with 403, and clears the cookie for your own site. The callback and sign-out answer with no-store.
  • An empty appOrigin stops the app at start-up, and both cookie-using plugins load in one app, in either order.

Sources

Frequently asked questions

How do I add authentication to a Fastify app?

Read the session in an onRequest hook and put the user on the request, then protect routes with a preHandler that answers 401 when nobody is signed in. Wrap the session plugin in fastify-plugin so every route sees it.

Should I check authentication in onRequest or preHandler in Fastify?

Read the session in onRequest, which runs first, and refuse requests in preHandler, which runs right before the route handler. Replying from a hook stops the request there, so the handler never runs.

Why does a Fastify auth plugin need fastify-plugin?

Fastify keeps each plugin's decorators and hooks inside that plugin. Wrapping it in fastify-plugin makes request.session and its hook apply to the whole app instead.

How do I set a cookie in Fastify?

Register @fastify/cookie, then call reply.setCookie(name, value, options) and read request.cookies. Its maxAge option is in seconds.

Can I use Supabase Auth with Fastify?

Yes. Create a client per request with @supabase/ssr, reading request.cookies and writing refreshed cookies with reply.setCookie, then call getClaims() in a hook to get the user's id.