Better Auth Instance
Learn how to use the Better Auth instance in your Next.js application
Auth Instance
The auth instance is a core concept in Better Auth that provides all the authentication functionality. In payload-better-auth, we create a typed wrapper around this instance to ensure type safety and seamless integration with Payload CMS.
Overview
The auth instance is created during the initialization of the Better Auth plugin within your Payload configuration. This process sets up the core authentication functionality, making it available for use throughout your application.
Features
The auth instance provides:
- Authentication methods (signIn, signOut, etc.)
- Session management
- User management
- Plugin-specific functionality
- Type-safe API endpoints
So basically all the goodies coming from Better Auth.
Usage in Next.js
The auth instance is available through the createAuthLayer
function. Here's how to use it:
Once created, you can use the auth instance in your components and API routes:
For more details on setting up and using the auth layer, see the createAuthLayer documentation.
Type Safety
The auth instance is fully typed based on your Better Auth configuration. This provides:
- Autocomplete for all available methods
- Type checking for method parameters
- Type inference for return values
- Compile-time error checking
Integration with Auth Layer
The auth instance works seamlessly with other auth layer features. Learn more about:
- Auth Checkers - Functions to check authentication state
- Auth Guards - Functions to protect routes and actions
Configuration
The auth instance is configured through your Better Auth options. Learn more about configuration in the Configuration section.
Best Practices
- Single Instance: Create the auth layer once and reuse it across your application
- Type Safety: Leverage TypeScript to catch errors at compile time
- Configuration: Keep your Better Auth options in a separate configuration file
- Error Handling: Always handle potential errors from auth instance methods
- Session Management: Use the auth instance's session methods for consistent session handling and leverage
checkers
andguards
wherever possible