supabase-auth-fastify.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.

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

Back to the guide