Skip to main content

Overview

@kubiks/otel-better-auth provides comprehensive OpenTelemetry instrumentation for Better Auth. Get complete authentication observability across all auth flows with a single line of code—OAuth, email/password, sessions, account management, and more.
Better Auth Trace Visualization
Visualize your authentication flows with detailed span information including operation type, user IDs, session IDs, auth methods, and success/failure status.

Installation

Peer Dependencies: @opentelemetry/api >= 1.9.0, better-auth >= 1.0.0

Quick Start

Instrumenting Better Auth is just a single call—wrap the instance you already create and every API method invocation is traced automatically. Keep the rest of your configuration unchanged.

Traced Operations

Sign In & Sign Up:
  • auth.http.oauth.callback.{provider} - OAuth callback with user ID
  • auth.http.signin.email - Email signin with user ID
  • auth.http.signup.email - Email signup with user ID
  • auth.http.oauth.initiate.{provider} - OAuth initiation
  • auth.http.signout - User signout
  • auth.http.get_session - Get session

Span Attributes

Each span includes rich context about the authentication operation:
User IDs and session IDs are captured where applicable to help with debugging and monitoring authentication flows.

Configuration

You can optionally customize the instrumentation:

Usage Examples

Basic Setup (Next.js App Router)

1

Configure Better Auth

lib/auth.ts
2

Create Auth Handler

app/api/auth/[...all]/route.ts
3

Use in Your App

All authentication operations are now automatically traced!

OAuth Authentication

Email/Password Authentication

Session Management

Account Management

Password Management

Email Management

Complete Integration Example

Here’s a full example of Better Auth with OpenTelemetry in a Next.js application:
lib/auth.ts
app/api/auth/[...all]/route.ts
app/actions/auth.ts

Best Practices

Always use Server Actions for authentication operations in Next.js:
Check for errors and provide appropriate feedback:
Always enable email verification for production:
Use descriptive tracer names for easier debugging:

Troubleshooting

Ensure OpenTelemetry is properly initialized before creating the auth instance:
User IDs are only captured for operations where the user is authenticated. For sign-in and sign-up, the user ID is captured after successful authentication.
Make sure you’re using the correct provider name in your Better Auth configuration. The provider name must match exactly (e.g., github, not GitHub).

Resources

Better Auth Documentation

Learn more about Better Auth

GitHub Repository

View source code and examples

npm Package

View package on npm

Report Issues

Found a bug? Let us know!

License

MIT