Crash Courses · Masters
Hooks
Automate logic with Payload lifecycle hooks — before/after operations.
10 min read+175 XP on completionCert: Payload CMS Crash Course
Tap any word in the text below to start reading from there.
Hooks
Hooks are Payload's automation layer — they run before or after database operations and can modify data, trigger side effects, or cancel operations.
Auto-generate Slug
// collections/Posts.ts
import type { CollectionConfig } from 'payload'
import slugify from 'slugify'
export const Posts: CollectionConfig = {
slug: 'posts',
hooks: {
beforeChange: [
async ({ data, operation }) => {
if (operation === 'create' && data.title) {
data.slug = slugify(data.title, { lower: true, strict: true })
}
return data
},
],
},
// ...
}After Create: Send Welcome Email
hooks: {
afterChange: [
async ({ doc, operation, req }) => {
if (operation === 'create') {
await sendWelcomeEmail(doc.email, doc.displayName)
}
return doc
},
],
},beforeRead: Transform Data
hooks: {
beforeRead: [
({ doc }) => {
return {
...doc,
// Add computed field
fullName: `${doc.firstName} ${doc.lastName}`,
// Mask sensitive data
email: doc.email?.replace(/(.)(.*)(@.*)/, (_, f, m, e) => f + '*'.repeat(m.length) + e),
}
},
],
},Field Hook
{
name: 'password',
type: 'text',
hooks: {
beforeChange: [
async ({ value }) => {
if (!value) return value
return hashPassword(value) // hash before saving
},
],
afterRead: [
() => undefined, // never return the hash
],
},
}Reading progress
0% read
In this module
beforeChange
afterChange
beforeRead
Hook context
0%