About Data Hooks

Data hooks run custom code before or after specific interactions with your collections. Hooks let you intercept database operations at key points in their lifecycle. This allows you to implement custom logic, validation, and computation without modifying the core data operations.

You can use hooks to:

  • Validate data: Check that incoming data meets requirements before it's saved.
  • Transform data: Modify items automatically, such as formatting text or calculating fields.
  • Enforce business rules: Apply custom logic based on business needs.
  • Update related data: Modify data in other collections or external systems when changes occur.
  • Integrate systems: Trigger external APIs or services when data changes.

You can currently create hooks only through the Velo API, but they trigger for any data operation. This includes operations you perform through:

  • The wix-data Velo API
  • The Data API of the SDK
  • The REST Data API
  • Datasets
  • Manual operations through the editor and dashboard.

Hook types

There are 3 main categories of hooks that run at different points in the data operation lifecycle. All hooks receive parameters specific to their type along with a context object, and must return appropriate values as described in the hooks reference documentation.

Before hooks

Before hooks run immediately before a data operation executes. They can modify the data being processed or block the operation by returning a rejected promise. This makes them ideal for validation, data transformation, and access control.

After hooks

After hooks run immediately after a data operation completes successfully. They can modify the returned results but can't affect what's actually stored in the database. After hooks are useful for post-processing results, calculated data, and updating related data in other collections or external systems.

Failure hooks

Failure hooks run when data operations encounter errors. They help with error handling, cleanup operations, and providing custom error responses to site visitors.

Hook conventions

Data hooks must always follow the naming and file conventions listed below.

File location

All data hooks must be defined in a file named data.js located in a site's backend.

Function naming

Hook functions use a specific naming pattern that combines the collection name with the hook type:

Copy

For example, if you have a collection with the ID Listings and want to create a beforeInsert hook:

Copy

See also

Did this help?