{"id":16619,"library":"fastify-better-auth","title":"Fastify Integration for Better Auth","description":"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.","status":"active","version":"1.2.0","language":"javascript","source_language":"en","source_url":"https://github.com/flaviodelgrosso/fastify-better-auth","tags":["javascript","fastify","better-auth","auth","authentication","plugin","typescript"],"install":[{"cmd":"npm install fastify-better-auth","lang":"bash","label":"npm"},{"cmd":"yarn add fastify-better-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add fastify-better-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core authentication library that this plugin integrates with Fastify.","package":"better-auth","optional":false},{"reason":"The web framework this plugin is built for; required for plugin registration and functionality.","package":"fastify","optional":false}],"imports":[{"note":"Primarily designed for ESM usage, with `import` being the standard. CommonJS `require` is not officially supported or typically used.","wrong":"const FastifyBetterAuth = require('fastify-better-auth');","symbol":"FastifyBetterAuth","correct":"import FastifyBetterAuth from 'fastify-better-auth';"},{"note":"Use `import type` for type-only imports to ensure they are removed during compilation, preventing potential runtime issues or unnecessary bundles.","wrong":"import { FastifyBetterAuthOptions } from 'fastify-better-auth';","symbol":"FastifyBetterAuthOptions","correct":"import { type FastifyBetterAuthOptions } from 'fastify-better-auth';"},{"note":"`getAuthDecorator` is a named export providing a type-safe way to access the `better-auth` instance from the Fastify decorator.","wrong":"const { getAuthDecorator } = require('fastify-better-auth');","symbol":"getAuthDecorator","correct":"import { getAuthDecorator } from 'fastify-better-auth';"}],"quickstart":{"code":"import { betterAuth } from 'better-auth';\nimport { drizzleAdapter } from 'better-auth/adapters/drizzle';\nimport type { FastifyInstance } from 'fastify';\nimport Fastify from 'fastify';\nimport FastifyBetterAuth from 'fastify-better-auth';\nimport fp from 'fastify-plugin';\n\n// Mock DB for demonstration; replace with your actual Drizzle ORM client\nconst db = {};\n\n// 1. Create the Better Auth instance\nexport const auth = betterAuth({\n  trustedOrigins: [process.env.AUTH_URL ?? 'http://localhost:3000'],\n  database: drizzleAdapter(db as any, { // Cast db to any for mock simplicity\n    provider: 'pg',\n    usePlural: true,\n  }),\n  emailAndPassword: {\n    enabled: true,\n  },\n});\n\n// 2. Define and register the plugin using fastify-plugin\nasync function authPlugin(fastify: FastifyInstance) {\n  await fastify.register(FastifyBetterAuth, { auth });\n  fastify.get('/protected', async (request, reply) => {\n    // Example of accessing the auth instance, though this route is not protected by default\n    // const authInstance = fastify.getAuthDecorator(); \n    return { message: 'Hello from a route. Auth routes are registered at /api/auth/*' };\n  });\n}\n\nconst registeredAuthPlugin = fp(authPlugin, {\n  name: 'auth-plugin',\n});\n\n// 3. Set up and start your Fastify application\nconst fastify = Fastify({ logger: true });\n\nfastify.register(registeredAuthPlugin);\n\nconst start = async () => {\n  try {\n    await fastify.listen({ port: 3000 });\n    console.log('Server listening on http://localhost:3000');\n  } catch (err) {\n    fastify.log.error(err);\n    process.exit(1);\n  }\n};\n\nstart();","lang":"typescript","description":"Demonstrates how to initialize a `better-auth` instance and register it as a Fastify plugin, providing authentication routes and instance access."},"warnings":[{"fix":"Upgrade your Node.js environment to version 23.10.0 or newer. Consider using a Node.js version manager like `nvm` or `volta`.","message":"This package requires Node.js version 23.10.0 or higher. Running on older Node.js versions will result in installation failures or runtime errors.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Ensure that `fastify` and `better-auth` are installed at versions `5.x` and `1.x` respectively. Check your `package.json` for correct peer dependency resolution.","message":"The plugin has strict peer dependency requirements for `fastify@5.x` and `better-auth@1.x`. Incompatible versions of these libraries may lead to runtime errors or unexpected behavior.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Always prefer `import { getAuthDecorator } from 'fastify-better-auth';` and call it to retrieve the `better-auth` instance in your handlers or hooks.","message":"While module augmentation for TypeScript is possible, `getAuthDecorator()` is the recommended and type-safe way to access the `better-auth` instance from Fastify, especially when plugins extend the auth instance.","severity":"gotcha","affected_versions":">=1.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Upgrade Node.js to version 23.10.0 or higher (e.g., using `nvm install 23 && nvm use 23`).","cause":"Your Node.js environment is older than the minimum required version 23.10.0.","error":"Error: The package 'fastify-better-auth' requires a Node.js version >= 23.10.0. You are using vX.Y.Z."},{"fix":"Install the `better-auth` package: `npm install better-auth@1.x` or `yarn add better-auth@1.x`.","cause":"The peer dependency `better-auth` is not installed or not resolvable by your package manager.","error":"Error: Cannot find module 'better-auth'"},{"fix":"Ensure you pass an `auth` object when registering the plugin: `fastify.register(FastifyBetterAuth, { auth: yourAuthInstance });`","cause":"The `auth` option, which expects an initialized `better-auth` instance, was not provided to the plugin.","error":"FastifyError: FST_ERR_BAD_PLUGIN_OPTS: Plugin 'fastify-better-auth' requires a 'auth' option"},{"fix":"Import `getAuthDecorator` from the package and call it: `import { getAuthDecorator } from 'fastify-better-auth'; const authInstance = getAuthDecorator(fastify);`","cause":"You are trying to access `getAuthDecorator` directly on the `fastify` instance, but it's an exported utility function, not a decorator on the instance itself.","error":"Property 'getAuthDecorator' does not exist on type 'FastifyInstance<any, any, any, Logger, RawServerDefault>'."}],"ecosystem":"npm"}