createAuthLayer
Learn how to use the createAuthLayer function to set up authentication in your Next.js application
createAuthLayer 🛠️
The createAuthLayer
function is the core of Better Auth's Next.js integration. It provides a set of pre-built helpers that make it easy to implement authentication checks and guards in your Next.js actions, routes and components.
Setup 🔧
First, create an auth layer in your Next.js project:
Better Auth Integration
This setup is similar to Better Auth's lib/auth.ts
file, but with a key difference: you don't need to create a Better Auth instance manually using betterAuth({...})
. The payload-better-auth plugin automatically creates and manages the Better Auth instance for you. The createAuthLayer
function simply provides access to this pre-configured instance along with additional helpers.
Available Helpers 🎯
The createAuthLayer
function returns several helpers:
Better Auth Instance
auth
: Better Auth Instance
Checkers
isAuth
: Check if user is authenticatedisGuest
: Check if user is a guest (not authenticated)isUser
: Check if user is logged inisAdmin
: Check if user is an adminisRole
: Check if user has specific role
Guards
guardAuth
: Protect and redirect if user is not authenticatedguardGuest
: Protect and redirect if user is a guest (not authenticated)guardUser
: Protect and redirect if user is logged inguardAdmin
: Protect and redirect if user is an adminguardRole
: Protect and redirect if user has specific role
Usage Examples
Using in Components
Best 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