Process Data with Hooks

Data hooks let you run custom code before or after data operations. This article shows you how to create hooks that validate incoming data and calculate derived values.

Before you begin

Make sure you understand the basics of data hooks and their conventions.

Validate data with a before hook

Before hooks run immediately before a data operation executes. They're ideal for validating and transforming data before it's saved to a collection.

This example shows how to create a beforeInsert hook that validates real estate listing data:

  1. Open your site's backend/data.js file or create one if it doesn't already exist.

  2. Add a beforeInsert hook for your Listings collection:

    Copy
  3. Test the hook by inserting a listing item from the editor, dashboard, or using the Data API. The hook validates that a valid price is present, transforms the data by trimming and uppercasing the title, and sets default values for optional fields.

Calculate derived data with an after hook

After hooks run immediately after a data operation completes successfully. They're useful for calculating derived values and modifying the returned results.

This example shows how to create an afterQuery hook that calculates a real estate listing's price per square foot:

  1. Open your site's backend/data.js file or create one if it doesn't already exist.

  2. In your backend/data.js file, add an afterQuery hook:

    Copy
  3. Test the hook by querying listing items from the editor, dashboard, or using the Data API. The hook calculates the price per square foot and includes it in the returned result.

See also

Did this help?