Skip to main content
Hooks are middleware functions that run before, after, or on errors of service method calls. They provide a powerful way to add cross-cutting concerns like validation, authorization, logging, and data manipulation.

Hook Types

Feathers supports four types of hooks:
declarations.ts:359
Before hooks run before the service method:
Use cases:
  • Input validation
  • Authentication checks
  • Data transformation
  • Setting default values

Hook Context

Every hook receives a context object with information about the service call:
declarations.ts:363-444

Registering Hooks

Service Hooks

Register hooks for specific service methods:
hooks.ts:214-234

Application Hooks

Register hooks that run for all services:
application.ts:206-223

Multiple Registration Formats

Hook Execution Order

Hooks execute in a specific order:
hooks.ts:159-164
If an error occurs at any point, the execution switches to error hooks in reverse order.

Common Hook Patterns

Authentication

Authorization

Validation

Remove Fields

Populate Associations

Soft Delete

Caching

Skipping Service Methods

Set context.result in a before hook to skip the actual service method:

Error Handling in Hooks

Throwing Errors

Handling Errors

hooks.ts:39-50

TypeScript Support

Best Practices

  1. Keep hooks focused - Each hook should do one thing well
  2. Make hooks reusable - Use factory functions for configurable hooks
  3. Order matters - Place authentication/authorization first
  4. Return context - Always return the context object (except around hooks)
  5. Use async/await - Avoid promise chains
  6. Handle errors properly - Use error hooks for cleanup
  7. Avoid side effects - Be careful with mutations
  8. Test hooks independently - Unit test hooks separately from services

Next Steps

Events

Learn about real-time events

Errors

Master error handling in Feathers