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/nextjs'
import config from '@/payload.config'
import { payloadBetterAuthConfig } from '@/payload-better-auth.config'
export const {
// accessor for the betterAuth instance (payload.betterAuth)
getAuth,
// checkers
isAuth,
isGuest,
isUser,
isAdmin,
isRole,
// guards
guardAuth,
// guardGuest,
// guardUser,
// guardAdmin,
// guardRole,
} = createAuthLayer(config, payloadBetterAuthConfig)Import from the /nextjs subpath
createAuthLayer is exported from @b3nab/payload-better-auth/nextjs, not from the package root. Importing it from the root was removed in 0.12 - see Migrating to 0.12 for the background.
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 creates the instance when Payload boots and manages it for you as payload.betterAuth; getAuth() returns exactly that instance.
Type inference
Once your project registers its plugin options (see Auth Instance), 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
getAuth: async accessor for the Better Auth instance (payload.betterAuth)
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
Create the auth layer once, in a single file, and import its helpers from there across the app.