Database Hooks
Configure database hooks to run custom logic before and after database operations.
Database Hooks Integration
GoBetterAuth provides powerful hooks to let you run custom logic before and after database operations for users, accounts, sessions, verifications and more. This allows you to integrate with your own systems, perform validations, trigger side effects, or log activity.
Example: Logging User Creation
Suppose you want to log every time a user is created in your system. You can use the BeforeCreate or AfterCreate hooks in the UserDatabaseHooksConfig.
import (
"log"
gobetterauth "github.com/GoBetterAuth/go-better-auth"
gobetterauthconfig "github.com/GoBetterAuth/go-better-auth/config"
gobetterauthmodels "github.com/GoBetterAuth/go-better-auth/models"
)
func logUserCreation(user gobetterauthmodels.User) error {
log.Printf("New user created - ID: %s, Email: %s", user.ID, user.Email)
return nil
}
config := gobetterauthconfig.NewConfig(
gobetterauthconfig.WithDatabaseHooks(gobetterauthmodels.DatabaseHooksConfig{
Users: &gobetterauthmodels.UserDatabaseHooksConfig{
AfterCreate: logUserCreation,
},
}),
)Available Database Hooks
You can hook into the following events:
- Users:
BeforeCreate,AfterCreate,BeforeUpdate,AfterUpdate - Accounts:
BeforeCreate,AfterCreate,BeforeUpdate,AfterUpdate - Sessions:
BeforeCreate,AfterCreate - Verifications:
BeforeCreate,AfterCreate
Each hook receives a pointer to the entity being created/updated (for Before*), or the entity itself (for After*). Return an error to abort the operation.
How to Integrate
- Implement your hook functions matching the required signature.
- Pass them to the appropriate field in the
DatabaseHooksConfigwhen creating your GoBetterAuth config. - Return an error from your hook to abort the operation, or
nilto continue.
See the Config Reference for the full structure and all available hooks.
