Registry / auth-security / nestjs-better-auth

nestjs-better-auth

JSON →
library0.6.4jsnpmunverified

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'.

npm install nestjs-better-auth
INSTALL
IMPORT
SIG · NESTJS-BETTER-AUTH
N
nestjs-better-auth
auth-securityjavascriptv0.6.4
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

BetterAuthModule
import { BetterAuthModule } from 'nestjs-better-auth';
const { BetterAuthModule } = require('nestjs-better-auth');
While this version retains CommonJS compatibility, ESM imports are standard for modern NestJS. The module is configured via `.forRoot()` or `.forRootAsync()`.
BetterAuthGuard
import { BetterAuthGuard } from 'nestjs-better-auth';
const { BetterAuthGuard } = require('nestjs-better-auth');
Used as an injectable provider, often globally with `APP_GUARD`, to protect routes.
CurrentUserSession
import { CurrentUserSession } from 'nestjs-better-auth';
import CurrentUserSession from 'nestjs-better-auth';
A named decorator for accessing authenticated user and session data from the request context.
BetterAuthUserSession
import { BetterAuthUserSession } from 'nestjs-better-auth';
TypeScript type definition for the object returned by `@CurrentUserSession()`.

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.

// main.ts (application entry point) import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule, { // CRITICAL: Disable NestJS's built-in body parser for better-auth to process raw requests. bodyParser: false, }); await app.listen(process.env.PORT ?? 3000); } bootstrap(); // app.module.ts (main application module) import { Module } from '@nestjs/common'; import { BetterAuthModule, BetterAuthGuard, CurrentUserSession, BetterAuthUserSession } from 'nestjs-better-auth'; import { APP_GUARD } from '@nestjs/core'; // Required for global guards import { Controller, Get, SetMetadata } from '@nestjs/common'; // Define a decorator to mark public routes, bypassing global authentication const PublicRouteToken = Symbol('publicRoute'); const IsPublic = () => SetMetadata(PublicRouteToken, true); @Controller() class MyController { @IsPublic() @Get('public') publicRoute() { return { message: 'This route is publicly accessible without authentication.' }; } @Get('me') getMe( @CurrentUserSession() userAndSession: BetterAuthUserSession, @CurrentUserSession('user') user: BetterAuthUserSession['user'], @CurrentUserSession('session') session: BetterAuthUserSession['session'], ) { // In a real app, the BetterAuthGuard would prevent unauthenticated access. // Here, we return session details for the authenticated user. return { user, session, message: 'Authenticated user session data.' }; } } @Module({ imports: [ BetterAuthModule.forRoot({ // Configure which metadata key marks public routes (to skip global auth) skipAuthDecoratorMetadataKey: PublicRouteToken, // Provide configuration for the underlying better-auth library betterAuthConfig: { emailAndPassword: { enabled: true, // Example: Enable email and password authentication }, // ... add more better-auth specific configurations here }, }), ], providers: [ // Apply BetterAuthGuard globally to protect all routes by default { provide: APP_GUARD, useClass: BetterAuthGuard, }, ], controllers: [MyController], }) export class AppModule {}
Debug
Known issues
gotchaThe `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.
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.
affects: <=0.6.4
breakingWhen 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.
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).
affects: >=0.6.0 (if peer `better-auth` >=1.2.11)
breakingThis 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.
fix
Modify `main.ts` to include `bodyParser: false` in `NestFactory.create()` options: `const app = await NestFactory.create(AppModule, { bodyParser: false });`
affects: >=0.6.0
deprecatedThe 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.
fix
Consider preparing your project for ESM migration, or closely monitor release notes for the breaking change announcement.
affects: >=0.6.0 (future versions will break)
gotchaAs 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.
fix
Always consult the project's changelog or GitHub releases when upgrading between minor versions to understand potential breaking changes and necessary adaptations.
affects: >=0.0.0
gotchaWhen `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.
fix
Define a custom decorator (`@IsPublic()`) and configure it in `BetterAuthModule.forRoot({ skipAuthDecoratorMetadataKey: PublicRouteToken })`. Apply this decorator to any route that should bypass authentication.
affects: >=0.6.0
gotchaThe `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.
fix
Refer to the official `better-auth` documentation for comprehensive configuration options and best practices. Thoroughly test authentication flows after any configuration changes.
affects: >=0.6.0
Errors
Common errors & fixes
Error: Nest can't find the BetterAuthModule provider (when processing BetterAuthModule).
The `BetterAuthModule` has not been correctly imported into an `AppModule` or a feature module, or `forRoot()`/`forRootAsync()` was not called.
fix
Ensure `BetterAuthModule.forRoot({...})` or `BetterAuthModule.forRootAsync({...})` is present in the `imports` array of your `AppModule` or relevant feature module.
Cannot read properties of undefined (reading 'user')` or `TypeError: Cannot read properties of undefined (reading 'session')` when using `@CurrentUserSession()`
The `@CurrentUserSession` decorator was used on a route that was not authenticated, or the authentication process failed, resulting in no active session being available.
fix
Ensure the route is protected by `BetterAuthGuard` and the user is successfully authenticated before attempting to access session data via `@CurrentUserSession`.
Error [ERR_REQUIRE_ESM]: require() of ES Module .../jose/dist/webapi/index.js from .../better-auth/... not supported.
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`).
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.
Upgrade
Version history
0.6.4latest on npm
Audit
Dependencies
@nestjs/commonrequiredCore NestJS dependency for module and decorators.
@nestjs/corerequiredCore NestJS dependency for application bootstrapping and global guards.
better-authrequiredThe foundational authentication and authorization library that this module wraps. Essential for all functionality.
@nestjs/graphqloptionalRequired only if GraphQL context integration is desired.
Agent activity
7 hits · last 30 days
node
6
OpenAI (training)
1
Resources