session-plugin.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.

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

Back to the guide