Guards
Learn about the authentication guards available in Better Auth
Guards 🛡️
Guards are functions that protect your routes and components from unauthorized access. They are returned by the createAuthLayer
function and can be used in various parts of your Next.js application.
Available Guards 🎯
guardAuth
The guardAuth
guard verifies if a user has an active session and returns session information. If redirectUrl
is provided and the user is not authenticated, it will automatically redirect to the specified URL:
guardGuest
The guardGuest
guard ensures that a user is not authenticated. If redirectUrl
is provided and the user is authenticated, it will automatically redirect to the specified URL:
guardUser
The guardUser
guard verifies that a user is authenticated and has a valid user record. If redirectUrl
is provided and the user is not authenticated or doesn't have a user
role, it will automatically redirect to the specified URL:
guardAdmin
The guardAdmin
guard ensures that a user is authenticated and has admin privileges. If redirectUrl
is provided and the user is not authenticated or doesn't have admin
role, it will automatically redirect to the specified URL:
guardRole
The guardRole
guard verifies that a user has a specific role. If redirectUrl
is provided and the user is not authenticated or doesn't have the specified role, it will automatically redirect to the specified URL:
Usage Examples 📝
Server components
Route Handlers
Error Handling 🚨
Guards return a result object that indicates whether the user has a valid session. You should check the hasSession
property to determine if the user is authorized. If you provide a redirectUrl
, the guard will handle the redirection automatically when the user is not authorized: