Made with Supabase

Supabase Plugin for Fastify

A Fastify plugin to use authenticated Supabase clients in your API.


Install with your favorite package manager.

pnpm add @psteinroe/fastify-supabase

If your package manager does not install peer dependencies automatically, you need to install them too

pnpm add @fastify/jwt @supabase/supabase-js

Quick Start

First, register @fastify/jwt with your Supabase JWT secret. You can obtain it from Supabase Studio.

import fastifyJWT from "@fastify/jwt";

fastify.register(fastifyJWT, {

Then, register the Supabase plugin.

import fastifySupabase from "@psteinroe/fastify-supabase";

fastify.register(fastifySupabase, {
  // you can pass any `SupabaseClientOptions`
  options: {},

You can now access a SupabaseClient authenticated as the service role directly on the Fastify instance with fastify.supabaseClient.

To protect a route and use a user-authenticated SupabaseClient, create a onRequest route handler to verify the JWT. Note that this is a @fastify/jwt feature.

import { onRequestHookHandler } from "fastify";

export const verifyApiKey: onRequestHookHandler = async (request) = {
  await request.jwtVerify();

Now pass the hook to the route handler. You can now access either a client authenticated with the service role via the Fastify instance, or a user-authenticated client via the request. Thanks to @fastify/jwt, you can also access the Supabase User object on the request.

import { FastifyInstance } from "fastify";

import { verifyApiKey } from "../helpers/verify";

export default async function routes(fastify: FastifyInstance) {
  fastify.get("/health", {
    onRequest: [verifyApiKey],
    handler: async (request, reply) = {
      // authenticated as the user that is making the request
      const { data } = request.supabaseClient.from("article").select("*");

      // authenticated with service role
      const { data } = fastify.supabaseClient.from("article").select("*");

      // access the `User` object on the request
      const tenantId = request.user.app_metadata.tenantId;

      return reply.send("OK");

Thats it!

Related Projects

A project by Zernonia