Field Hooks

Field Hooks are Hooks that run on Documents on a per-field basis. They allow you to execute your own logic during specific events of the Document lifecycle. Field Hooks offer incredible potential for isolating your logic from the rest of your Collection Hooks and Global Hooks.

To add Hooks to a Field, use the hooks property in your Field Config:

1
import type { Field } from 'payload';
2
3
export const FieldWithHooks: Field = {
4
// ...
5
hooks: {
6
// ...
7
},
8
}

Config Options

All Field Hooks accept an array of synchronous or asynchronous functions. These functions can optionally modify the return value of the field before the operation continues. All Field Hooks are formatted to accept the same arguments, although some arguments may be undefined based the specific hook type.

To add hooks to a Field, use the hooks property in your Field Config:

1
import type { Field } from 'payload';
2
3
const FieldWithHooks: Field = {
4
name: 'name',
5
type: 'text',
6
hooks: {
7
beforeValidate: [(args) => {...}],
8
beforeChange: [(args) => {...}],
9
beforeDuplicate: [(args) => {...}],
10
afterChange: [(args) => {...}],
11
afterRead: [(args) => {...}],
12
}
13
}

The following arguments are provided to all Field Hooks:

OptionDescription
collectionThe Collection in which this Hook is running against. If the field belongs to a Global, this will be null.
contextCustom context passed between Hooks. More details.
dataIn the afterRead hook this is the full Document. In the create and update operations, this is the incoming data passed through the operation.
fieldThe Field which the Hook is running against.
findManyBoolean to denote if this hook is running against finding one, or finding many within the afterRead hook.
globalThe Global in which this Hook is running against. If the field belongs to a Collection, this will be null.
operationThe name of the operation that this hook is running within. Useful within beforeValidate, beforeChange, and afterChange hooks to differentiate between create and update operations.
originalDocIn the update operation, this is the Document before changes were applied. In the afterChange hook, this is the resulting Document.
overrideAccessA boolean to denote if the current operation is overriding Access Control.
pathThe path to the Field in the schema.
previousDocIn the afterChange Hook, this is the Document before changes were applied.
previousSiblingDocThe sibling data of the Document before changes being applied, only in beforeChange and afterChange hook.
previousValueThe previous value of the field, before changes, only in beforeChange and afterChange hooks.
reqThe Web Request object. This is mocked for Local API operations.
schemaPathThe path of the Field in the schema.
siblingDataThe data of sibling fields adjacent to the field that the Hook is running against.
siblingDocWithLocalesThe sibling data of the Document with all Locales.
valueThe value of the Field.

beforeValidate

Runs before the update operation. This hook allows you to pre-process or format field data before it undergoes validation.

1
import type { Field } from 'payload'
2
3
const usernameField: Field = {
4
name: 'username',
5
type: 'text',
6
hooks: {
7
beforeValidate: [
8
({ value }) => {
9
// Trim whitespace and convert to lowercase
10
return value.trim().toLowerCase()
11
},
12
],
13
},
14
}

In this example, the beforeValidate hook is used to process the username field. The hook takes the incoming value of the field and transforms it by trimming whitespace and converting it to lowercase. This ensures that the username is stored in a consistent format in the database.

beforeChange

Immediately following validation, beforeChange hooks will run within create and update operations. At this stage, you can be confident that the field data that will be saved to the document is valid in accordance to your field validations.

1
import type { Field } from 'payload'
2
3
const emailField: Field = {
4
name: 'email',
5
type: 'email',
6
hooks: {
7
beforeChange: [
8
({ value, operation }) => {
9
if (operation === 'create') {
10
// Perform additional validation or transformation for 'create' operation
11
}
12
return value
13
},
14
],
15
},
16
}

In the emailField, the beforeChange hook checks the operation type. If the operation is create, it performs additional validation or transformation on the email field value. This allows for operation-specific logic to be applied to the field.

afterChange

The afterChange hook is executed after a field's value has been changed and saved in the database. This hook is useful for post-processing or triggering side effects based on the new value of the field.

1
import type { Field } from 'payload'
2
3
const membershipStatusField: Field = {
4
name: 'membershipStatus',
5
type: 'select',
6
options: [
7
{ label: 'Standard', value: 'standard' },
8
{ label: 'Premium', value: 'premium' },
9
{ label: 'VIP', value: 'vip' },
10
],
11
hooks: {
12
afterChange: [
13
({ value, previousValue, req }) => {
14
if (value !== previousValue) {
15
// Log or perform an action when the membership status changes
16
console.log(
17
`User ID ${req.user.id} changed their membership status from ${previousValue} to ${value}.`,
18
)
19
// Here, you can implement actions that could track conversions from one tier to another
20
}
21
},
22
],
23
},
24
}

In this example, the afterChange hook is used with a membershipStatusField, which allows users to select their membership level (Standard, Premium, VIP). The hook monitors changes in the membership status. When a change occurs, it logs the update and can be used to trigger further actions, such as tracking conversion from one tier to another or notifying them about changes in their membership benefits.

afterRead

The afterRead hook is invoked after a field value is read from the database. This is ideal for formatting or transforming the field data for output.

1
import type { Field } from 'payload'
2
3
const dateField: Field = {
4
name: 'createdAt',
5
type: 'date',
6
hooks: {
7
afterRead: [
8
({ value }) => {
9
// Format date for display
10
return new Date(value).toLocaleDateString()
11
},
12
],
13
},
14
}

Here, the afterRead hook for the dateField is used to format the date into a more readable format using toLocaleDateString(). This hook modifies the way the date is presented to the user, making it more user-friendly.

beforeDuplicate

The beforeDuplicate field hook is called on each locale (when using localization), when duplicating a document. It may be used when documents having the exact same properties may cause issue. This gives you a way to avoid duplicate names on unique, required fields or when external systems expect non-repeating values on documents.

This hook gets called after beforeChange hooks are called and before the document is saved to the database.

By Default, unique and required text fields Payload will append "- Copy" to the original document value. The default is not added if your field has its own, you must return non-unique values from your beforeDuplicate hook to avoid errors or enable the disableDuplicate option on the collection. Here is an example of a number field with a hook that increments the number to avoid unique constraint errors when duplicating a document:

1
import type { Field } from 'payload'
2
3
const numberField: Field = {
4
name: 'number',
5
type: 'number',
6
hooks: {
7
// increment existing value by 1
8
beforeDuplicate: [({ value }) => {
9
return (value ?? 0) + 1
10
}],
11
}
12
}

TypeScript

Payload exports a type for field hooks which can be accessed and used as follows:

1
import type { FieldHook } from 'payload'
2
3
// Field hook type is a generic that takes three arguments:
4
// 1: The document type
5
// 2: The value type
6
// 3: The sibling data type
7
8
type ExampleFieldHook = FieldHook<ExampleDocumentType, string, SiblingDataType>
9
10
const exampleFieldHook: ExampleFieldHook = (args) => {
11
const {
12
value, // Typed as `string` as shown above
13
data, // Typed as a Partial of your ExampleDocumentType
14
siblingData, // Typed as a Partial of SiblingDataType
15
originalDoc, // Typed as ExampleDocumentType
16
operation,
17
req,
18
} = args
19
20
// Do something here...
21
22
return value // should return a string as typed above, undefined, or null
23
}
Next

Context