auth-routes.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.

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();
  });
};

Back to the guide