What are Hooks?
Hooks are middleware functions that run before, after, or around service methods. They allow you to add validation, authorization, data transformation, and other business logic in a composable and reusable way.Hook Types
Feathers supports four types of hooks:- before - Run before the service method
- after - Run after the service method completes successfully
- error - Run when the service method throws an error
- around - Wrap the entire service method call
Basic Hook Usage
Register hooks on a service using the.hooks() method:
Hook Context
Every hook receives acontext object containing information about the service call:
Hook Context
Modifying the Context
Hooks can modify the context to change behavior:Application-Level Hooks
Register hooks that run for all services:Application Hooks
Around Hooks
Around hooks wrap the entire service method call and give you control over the execution flow:Around Hooks
Around hooks must call
await next() to continue execution. If you don’t call next(), the service method won’t execute.Common Hook Patterns
Validation Hooks
Validate data before it reaches the service:Validation
Authorization Hooks
Check permissions before allowing operations:Authorization
Data Sanitization
Clean and transform data:Sanitization
Adding User Context
Automatically associate records with the current user:User Context
Schema-Based Hooks
Feathers provides schema-based validation and resolution hooks:Hook Execution Order
Hooks execute in a specific order:1
Application-Level Around Hooks
Around hooks registered at the application level run first
2
Service-Level Around Hooks
Around hooks registered at the service level
3
Application-Level Before Hooks
Before hooks from
app.hooks()4
Service-Level Before Hooks
Before hooks from
service.hooks()5
Service Method
The actual service method executes
6
Service-Level After Hooks
After hooks from
service.hooks()7
Application-Level After Hooks
After hooks from
app.hooks()Conditional Hooks
Run hooks only under certain conditions:Conditional Hooks
Async Hook Registration
You can register hooks as arrays for cleaner composition:Array-Based Hooks
Error Handling in Hooks
Handle errors gracefully in your hooks:Error Handling
Complete Hook Example
Here’s a complete example with validation, authorization, and data transformation:Complete Example