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:
import { createAuthLayer } from '@b3nab/payload-better-auth'
import config from '@/payload.config'
import { payloadBetterAuthConfig } from '@/payload-better-auth.config'
export const {
// betterAuth instance
auth,
// checkers
isAuth,
isGuest,
isUser,
isAdmin,
isRole,
// guards
guardAuth,
// guardGuest,
// guardUser,
// guardAdmin,
// guardRole,
} = createAuthLayer(config, payloadBetterAuthConfig)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 @b3nab/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.
Type inference
The returned auth is typed via InferBetterAuthInstance<O> where O is your plugin options. That means any Better Auth plugin you add under betterAuth.plugins (e.g. twoFactor, passkey, admin) is reflected in the auth.api.* typings out of the box: full autocomplete, no manual casting.
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 has theuserrole (shortcut forisRole({ role: 'user' }))isAdmin: 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
import { isAdmin } from '@/lib/auth'
export default async function ProtectedPage() {
const isAdminUser = await isAdmin()
if (!isAdminUser) {
return <div>Access denied</div>
}
return <div>Admin content</div>
}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