Installation
Learn how to install and configure Better Auth in your PayloadCMS project
Installation 🚀
This guide will walk you through installing and configuring Better Auth in your PayloadCMS project.
Prerequisites 📋
- Node.js 18 or later
- PayloadCMS v3 or later
- A running database (all PayloadCMS supported databases)
- Installed required packages, for the moment only better-auth is the only required package
npm install better-auth@1.2.7Better Auth Version Compatibility
payload-better-auth@0.8.x requires better-auth@1.2.7,
If you have some strange type errors verify both package versions.
Installation 💻
1. Install the package using your preferred package manager:
npm install payload-better-auth2. Create the plugin/better-auth config:
export const payloadBetterAuthConfig = {} as constBy default if you pass an empty object (as const is important) you will have out-of-the-box the following features:
- PayloadCMS Admin with email and password authentication
- PayloadCMS Admin with Two Factor Authentication (2FA for admins)
- OpenAPI auto documentation at
/api/auth/reference adminanduserRoles and default RBAC (from better-auth's admin plugin)
3. Import and configure the plugin in your PayloadCMS config:
import { buildConfig } from 'payload/config'
import { betterAuthPlugin } from '@payload-better-auth'
import { payloadBetterAuthConfig } from '@/lib/payload-better-auth.config'
export default buildConfig({
// ... your existing config
plugins: [
betterAuthPlugin(payloadBetterAuthConfig),
],
})Environment Variables 🔑
Create or update your .env file:
BETTER_AUTH_SECRET=your_generated_secretYou can generate a secure secret using:
openssl rand -base64 32Best Practices 📚
- Create a single auth layer instance and export it
- Use guards for route protection
- Use checkers for conditional rendering
- Handle errors appropriately
- Cache authentication state when possible