Fastify Integration for Better Auth

1.2.0 · active · verified Wed Apr 22

Fastify Better Auth is a Fastify plugin designed to seamlessly integrate the `better-auth` authentication library into Fastify applications. It automates the registration of all necessary authentication routes, typically under `/api/auth/*`, and decorates the Fastify instance with utilities to access the `better-auth` instance and manage session data. The current stable version is 1.2.0, with minor feature releases indicating active development. Key differentiators include its focus on type-safe decorator access to the auth instance via `getAuthDecorator()` and its direct compatibility with Fastify 5.x and Better Auth 1.x, simplifying setup for applications using these specific versions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize a `better-auth` instance and register it as a Fastify plugin, providing authentication routes and instance access.

import { betterAuth } from 'better-auth';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import type { FastifyInstance } from 'fastify';
import Fastify from 'fastify';
import FastifyBetterAuth from 'fastify-better-auth';
import fp from 'fastify-plugin';

// Mock DB for demonstration; replace with your actual Drizzle ORM client
const db = {};

// 1. Create the Better Auth instance
export const auth = betterAuth({
  trustedOrigins: [process.env.AUTH_URL ?? 'http://localhost:3000'],
  database: drizzleAdapter(db as any, { // Cast db to any for mock simplicity
    provider: 'pg',
    usePlural: true,
  }),
  emailAndPassword: {
    enabled: true,
  },
});

// 2. Define and register the plugin using fastify-plugin
async function authPlugin(fastify: FastifyInstance) {
  await fastify.register(FastifyBetterAuth, { auth });
  fastify.get('/protected', async (request, reply) => {
    // Example of accessing the auth instance, though this route is not protected by default
    // const authInstance = fastify.getAuthDecorator(); 
    return { message: 'Hello from a route. Auth routes are registered at /api/auth/*' };
  });
}

const registeredAuthPlugin = fp(authPlugin, {
  name: 'auth-plugin',
});

// 3. Set up and start your Fastify application
const fastify = Fastify({ logger: true });

fastify.register(registeredAuthPlugin);

const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
    console.log('Server listening on http://localhost:3000');
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();

view raw JSON →