npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

fastify-better-auth

v1.2.0

Published

Fastify plugin for better-auth implementation

Downloads

9,886

Readme

Fastify Better Auth

NPM version NPM downloads CI codecov

Fastify Better Auth is a Fastify plugin that simplifies the integration of the Better Auth library into your Fastify applications. This plugin automatically registers authentication routes and provides utilities to access the auth instance and session data in your application.

Features

  • 🚀 Easy integration with Better Auth
  • 🛡️ Automatic route registration for authentication endpoints
  • 🔧 Type-safe decorator access to auth instance
  • ⚡ Compatible with Fastify 5.x and Better Auth 1.x

Requirements

  • Fastify 5.x
  • Better Auth 1.x

Installation

npm install fastify-better-auth

Quick Start

1. Create the Better Auth instance

import { betterAuth } from 'better-auth';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';

export const auth = betterAuth({
  trustedOrigins: [process.env.AUTH_URL],
  database: drizzleAdapter(db, {
    provider: 'pg',
    usePlural: true,
  }),
  emailAndPassword: {
    enabled: true,
  },
});

2. Register the plugin

Option 1: Using fastify-plugin

import type { FastifyInstance } from 'fastify';
import FastifyBetterAuth from 'fastify-better-auth';
import fp from 'fastify-plugin';
import { auth } from './auth.js';

async function authPlugin(fastify: FastifyInstance) {
  await fastify.register(FastifyBetterAuth, { auth });
}

export default fp(authPlugin, {
  name: 'auth-plugin',
});

Option 2: Using Fastify Autoload

import FastifyBetterAuth, { type FastifyBetterAuthOptions } from 'fastify-better-auth';
import { auth } from './auth.js';

export const autoConfig: FastifyBetterAuthOptions = {
  auth
};

export default FastifyBetterAuth;

3. Start using authentication

Once registered, the plugin automatically creates authentication routes under /api/auth/* and decorates your Fastify instance with the auth utilities.

API Reference

Plugin Options

interface FastifyBetterAuthOptions<AuthOptions extends BetterAuthOptions = BetterAuthOptions> {
  auth: BetterAuthInstance<AuthOptions>;
}
  • auth: A Better Auth instance created with betterAuth()

Available Routes

The plugin automatically registers the following authentication routes:

  • POST /api/auth/sign-in - Sign in with email/password
  • POST /api/auth/sign-up - Create a new account
  • POST /api/auth/sign-out - Sign out the current user
  • GET /api/auth/session - Get current session
  • And all other Better Auth endpoints...

Advanced Usage

Accessing the Better Auth Instance

When registering the plugin, it decorates the Fastify instance with the Better Auth instance. You can use getAuthDecorator() to access the auth instance in your routes or hooks.

Note: getDecorator API provided by Fastify is the recommended way instead of using module augmentation. getAuthDecorator() is a wrapper around it and is generic and type-safe. It's recommended to use it with the type of the auth options you passed to the auth instance, especially if you're using plugins that extend the auth instance with additional methods.

import { getAuthDecorator } from 'fastify-better-auth';
import type { FastifyInstance } from 'fastify';

// In your route handler
fastify.get('/protected', async (request, reply) => {
  const auth = getAuthDecorator<typeof authOptions>(fastify);
  // Use auth.api methods here
});

Session Management

Here's how to create an authentication hook to protect routes and access session data:

import { fromNodeHeaders } from 'better-auth/node';
import type { FastifyInstance } from 'fastify';
import { getAuthDecorator } from 'fastify-better-auth';
import { auth } from './auth.js';

async function authHook(fastify: FastifyInstance) {
  // Decorate the request with session
  fastify.decorateRequest('session');

  fastify.addHook('onRequest', async (request, reply) => {
    const authInstance = getAuthDecorator<typeof auth.options>(fastify);
    const session = await authInstance.api.getSession({
      headers: fromNodeHeaders(request.headers),
    });

    if (!session?.user) {
      return reply.unauthorized('You must be logged in to access this resource.');
    }

    request.setDecorator('session', session);
  });
}

export default authHook;

Examples

Basic Authentication Route

import type { FastifyInstance } from 'fastify';
import { getAuthDecorator } from 'fastify-better-auth';

export default async function routes(fastify: FastifyInstance) {
  // Public route
  fastify.get('/health', async () => {
    return { status: 'ok' };
  });

  // Protected route
  fastify.get('/profile', {
    preHandler: async (request, reply) => {
      const auth = getAuthDecorator(fastify);
      const session = await auth.api.getSession({
        headers: fromNodeHeaders(request.headers),
      });

      if (!session?.user) {
        return reply.code(401).send({ error: 'Unauthorized' });
      }

      request.user = session.user;
    }
  }, async (request) => {
    return { user: request.user };
  });
}

Complete Example

You can find a complete working example in the fastify-forge template, which demonstrates:

  • Full authentication setup
  • Protected routes
  • Session management
  • Production-ready configuration

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Development

  1. Clone the repository
  2. Install dependencies: npm install
  3. Run tests: npm test
  4. Build the project: npm run build

Changelog

See CHANGELOG.md for details about changes in each version.

License

This project is licensed under the ISC License - see the LICENSE file for details.