{"id":16733,"library":"nestjs-better-auth","title":"NestJS Better Auth Module","description":"The `nestjs-better-auth` module (version `0.6.4`) integrates the `better-auth` authentication and authorization library into NestJS applications. It provides authentication guards for route protection and decorators for convenient access to authenticated user sessions. This module supports both Express v5 and Fastify HTTP adapters, along with comprehensive GraphQL context capabilities. While it currently maintains CommonJS compatibility, its README indicates a future transition to ESM. This specific package, maintained by `underfisk`, appears to have a slower release cadence compared to a related, more actively developed package (`@thallesp/nestjs-better-auth`) which is at version `2.x.x`. Users should be aware of this distinction when choosing their authentication solution, as `nestjs-better-auth@0.6.4` has not seen recent updates and features like 'Hooks' are still marked 'WIP'.","status":"maintenance","version":"0.6.4","language":"javascript","source_language":"en","source_url":"https://github.com/underfisk/nestjs-better-auth","tags":["javascript","better-auth","nestjs","auth","authentication","authorization","jwt","typescript"],"install":[{"cmd":"npm install nestjs-better-auth","lang":"bash","label":"npm"},{"cmd":"yarn add nestjs-better-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add nestjs-better-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core NestJS dependency for module and decorators.","package":"@nestjs/common","optional":false},{"reason":"Core NestJS dependency for application bootstrapping and global guards.","package":"@nestjs/core","optional":false},{"reason":"The foundational authentication and authorization library that this module wraps. Essential for all functionality.","package":"better-auth","optional":false},{"reason":"Required only if GraphQL context integration is desired.","package":"@nestjs/graphql","optional":true}],"imports":[{"note":"While this version retains CommonJS compatibility, ESM imports are standard for modern NestJS. The module is configured via `.forRoot()` or `.forRootAsync()`.","wrong":"const { BetterAuthModule } = require('nestjs-better-auth');","symbol":"BetterAuthModule","correct":"import { BetterAuthModule } from 'nestjs-better-auth';"},{"note":"Used as an injectable provider, often globally with `APP_GUARD`, to protect routes.","wrong":"const { BetterAuthGuard } = require('nestjs-better-auth');","symbol":"BetterAuthGuard","correct":"import { BetterAuthGuard } from 'nestjs-better-auth';"},{"note":"A named decorator for accessing authenticated user and session data from the request context.","wrong":"import CurrentUserSession from 'nestjs-better-auth';","symbol":"CurrentUserSession","correct":"import { CurrentUserSession } from 'nestjs-better-auth';"},{"note":"TypeScript type definition for the object returned by `@CurrentUserSession()`.","symbol":"BetterAuthUserSession","correct":"import { BetterAuthUserSession } from 'nestjs-better-auth';"}],"quickstart":{"code":"// main.ts (application entry point)\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, {\n    // CRITICAL: Disable NestJS's built-in body parser for better-auth to process raw requests.\n    bodyParser: false,\n  });\n  await app.listen(process.env.PORT ?? 3000);\n}\nbootstrap();\n\n// app.module.ts (main application module)\nimport { Module } from '@nestjs/common';\nimport { BetterAuthModule, BetterAuthGuard, CurrentUserSession, BetterAuthUserSession } from 'nestjs-better-auth';\nimport { APP_GUARD } from '@nestjs/core'; // Required for global guards\nimport { Controller, Get, SetMetadata } from '@nestjs/common';\n\n// Define a decorator to mark public routes, bypassing global authentication\nconst PublicRouteToken = Symbol('publicRoute');\nconst IsPublic = () => SetMetadata(PublicRouteToken, true);\n\n@Controller()\nclass MyController {\n  @IsPublic()\n  @Get('public')\n  publicRoute() {\n    return { message: 'This route is publicly accessible without authentication.' };\n  }\n\n  @Get('me')\n  getMe(\n    @CurrentUserSession() userAndSession: BetterAuthUserSession,\n    @CurrentUserSession('user') user: BetterAuthUserSession['user'],\n    @CurrentUserSession('session') session: BetterAuthUserSession['session'],\n  ) {\n    // In a real app, the BetterAuthGuard would prevent unauthenticated access.\n    // Here, we return session details for the authenticated user.\n    return { user, session, message: 'Authenticated user session data.' };\n  }\n}\n\n@Module({\n  imports: [\n    BetterAuthModule.forRoot({\n      // Configure which metadata key marks public routes (to skip global auth)\n      skipAuthDecoratorMetadataKey: PublicRouteToken,\n      // Provide configuration for the underlying better-auth library\n      betterAuthConfig: {\n        emailAndPassword: {\n          enabled: true, // Example: Enable email and password authentication\n        },\n        // ... add more better-auth specific configurations here\n      },\n    }),\n  ],\n  providers: [\n    // Apply BetterAuthGuard globally to protect all routes by default\n    {\n      provide: APP_GUARD,\n      useClass: BetterAuthGuard,\n    },\n  ],\n  controllers: [MyController],\n})\nexport class AppModule {}\n","lang":"typescript","description":"This quickstart demonstrates how to set up `nestjs-better-auth` globally, configure public routes, and access authenticated user sessions within a NestJS application. It includes the crucial step of disabling NestJS's default body parser for proper functionality and showcases the `@CurrentUserSession` decorator."},"warnings":[{"fix":"Evaluate `@thallesp/nestjs-better-auth` for newer features, ongoing maintenance, and potential bug fixes if active development is a priority. This may involve package name and import path changes.","message":"The `nestjs-better-auth` package (version `0.6.4`) is distinct from `@thallesp/nestjs-better-auth` (version `2.x.x`). The `underfisk/nestjs-better-auth` repository, corresponding to this package, shows limited recent activity. The `@thallesp` version appears to be a more actively maintained and updated alternative.","severity":"gotcha","affected_versions":"<=0.6.4"},{"fix":"For CommonJS projects, explicitly pin your `better-auth` dependency to version `1.2.10` or lower (`pnpm add better-auth@1.2.10`). Alternatively, migrate your NestJS project to use ECMAScript Modules (ESM).","message":"When using `nestjs-better-auth` in a CommonJS NestJS project, installing `better-auth` (the peer dependency) at version `1.2.11` or higher will cause an `ERR_REQUIRE_ESM` runtime error due to `better-auth`'s dependency on the ESM-only `jose` library.","severity":"breaking","affected_versions":">=0.6.0 (if peer `better-auth` >=1.2.11)"},{"fix":"Modify `main.ts` to include `bodyParser: false` in `NestFactory.create()` options: `const app = await NestFactory.create(AppModule, { bodyParser: false });`","message":"This module requires NestJS's built-in body parser to be explicitly disabled in your `main.ts` file for `better-auth` to correctly process incoming authentication requests. Failing to do so will result in authentication failures.","severity":"breaking","affected_versions":">=0.6.0"},{"fix":"Consider preparing your project for ESM migration, or closely monitor release notes for the breaking change announcement.","message":"The package's README explicitly states a future plan to transition to full ECMAScript Modules (ESM). While CommonJS is currently supported, this future change will be a significant breaking change for projects relying solely on CJS imports.","severity":"deprecated","affected_versions":">=0.6.0 (future versions will break)"},{"fix":"Always consult the project's changelog or GitHub releases when upgrading between minor versions to understand potential breaking changes and necessary adaptations.","message":"As a `0.x.x` version, `nestjs-better-auth` may introduce breaking changes between minor versions (e.g., `0.6.x` to `0.7.x`) without adhering to strict semantic versioning. Developers should review release notes carefully during upgrades.","severity":"gotcha","affected_versions":">=0.0.0"},{"fix":"Define a custom decorator (`@IsPublic()`) and configure it in `BetterAuthModule.forRoot({ skipAuthDecoratorMetadataKey: PublicRouteToken })`. Apply this decorator to any route that should bypass authentication.","message":"When `BetterAuthGuard` is registered globally (e.g., using `APP_GUARD`), all routes in your application become protected by default. Publicly accessible routes must be explicitly marked using the `skipAuthDecoratorMetadataKey` mechanism, or they will be unreachable.","severity":"gotcha","affected_versions":">=0.6.0"},{"fix":"Refer to the official `better-auth` documentation for comprehensive configuration options and best practices. Thoroughly test authentication flows after any configuration changes.","message":"The `betterAuthConfig` object passed to `BetterAuthModule.forRoot()` directly configures the underlying `better-auth` library. Incomplete or incorrect configurations here can lead to authentication malfunctions, security vulnerabilities, or unexpected application behavior.","severity":"gotcha","affected_versions":">=0.6.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `BetterAuthModule.forRoot({...})` or `BetterAuthModule.forRootAsync({...})` is present in the `imports` array of your `AppModule` or relevant feature module.","cause":"The `BetterAuthModule` has not been correctly imported into an `AppModule` or a feature module, or `forRoot()`/`forRootAsync()` was not called.","error":"Error: Nest can't find the BetterAuthModule provider (when processing BetterAuthModule)."},{"fix":"Ensure the route is protected by `BetterAuthGuard` and the user is successfully authenticated before attempting to access session data via `@CurrentUserSession`.","cause":"The `@CurrentUserSession` decorator was used on a route that was not authenticated, or the authentication process failed, resulting in no active session being available.","error":"Cannot read properties of undefined (reading 'user')` or `TypeError: Cannot read properties of undefined (reading 'session')` when using `@CurrentUserSession()`"},{"fix":"For CommonJS projects, downgrade `better-auth` to version `1.2.10` or lower by running `pnpm add better-auth@1.2.10` (or `npm install better-auth@1.2.10`). Alternatively, convert your NestJS project to use ECMAScript Modules.","cause":"This error occurs in CommonJS NestJS projects when `better-auth` (a peer dependency) version `1.2.11` or higher is installed, as it internally requires an ESM-only package (`jose`).","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module .../jose/dist/webapi/index.js from .../better-auth/... not supported."}],"ecosystem":"npm"}