When data in Directus requires immediate reaction—order validation, notification of a new submission, or synchronization with an external system—standard CMS features often fall short. Building custom Directus hook extensions embeds business logic directly into the core: you subscribe to CRUD, authentication, or file upload events and execute arbitrary code. This reduces latency by 30–50% compared to external API calls and simplifies architecture—no need to spin up a separate microservice for data processing. With over 5 years of Directus development experience and 50+ custom hooks built for 30+ clients, our team delivers reliable, performant solutions. Typical hook development costs range from $800 to $2,500, and clients report monthly savings of up to $5,000 on operational overhead. Contact us to discuss your task—we'll prepare an estimate within one day.
Why Custom Hooks Outperform External Services and Solve Common Problems
Custom hooks eliminate network call overhead—they run in the same Directus process, cutting latency by 30-50% and reducing TTFB. For example, an order validation hook checks stock in 5ms, while an external API call takes 50–100ms. This is critical for high-load projects. Typical challenges solved:
- Complex data validation—checking stock levels, relationship correctness, field uniqueness.
- Side effects—notifications to Slack/Telegram, audit logs, cache invalidation (3–5× faster than external calls).
- Integrations with ERP, CRM (e.g., 1C), payment gateways.
- Automation—slug generation, stock updates, scheduled reports via cron.
Getting Started with Directus Hooks
- Create file
extensions/hooks/custom/index.ts. - Export a function accepting
HookExtensionContext. - Call
filter('items.create', async (payload, meta, context) => { ... })to validate or modify data before save. - To cancel the operation, throw an error via
throw new Error('Message'). - Restart Directus—the hook is picked up automatically.
Through context.database (Knex instance) you can run direct SQL queries or use ItemsService for consistent collection access. The Directus Documentation recommends ItemsService, but direct Knex is fine for complex joins.
Event Types and When to Use Them
| Type | Description | Use Case |
|---|---|---|
action |
After the operation | Notifications, cache, integrations |
filter |
Before the operation (can modify data) | Validation, payload modification |
init |
On server startup | Configuration loading, connection initialization |
schedule |
On cron schedule | Daily reports, data cleanup |
Comparison: Action hooks run after DB write (async, non-blocking) and cannot modify data, while filter hooks run before write (sync, blocking) and can change payload.
Complete Hook Extension Example
// extensions/hooks/business-logic/index.ts
import type { HookExtensionContext } from '@directus/types'
import type { EventContext } from '@directus/types'
export default ({ action, filter, schedule }: HookExtensionContext) => {
// ===== AUTOMATIC SLUG GENERATION =====
filter('items.create', (payload, meta) => {
if (meta.collection === 'articles' && payload.title && !payload.slug) {
payload.slug = generateSlug(payload.title as string)
}
if (meta.collection === 'products' && payload.name && !payload.slug) {
payload.slug = generateSlug(payload.name as string)
}
return payload
})
// ===== VALIDATION =====
filter('items.create', async (payload, meta, context) => {
if (meta.collection !== 'orders') return payload
const { database } = context as EventContext & { database: any }
// Check product availability
if (payload.items && Array.isArray(payload.items)) {
for (const item of payload.items) {
const product = await database('products')
.where({ id: item.product_id })
.first()
if (!product) {
throw new Error(`Product ${item.product_id} not found`)
}
if (product.stock < item.quantity) {
throw new Error(`Insufficient stock for "${product.name}"`)
}
}
}
return payload
})
// ===== CACHE INVALIDATION =====
action('items.update', async ({ collection, keys, payload }) => {
const collectionsToRevalidate = ['articles', 'pages', 'products', 'settings']
if (!collectionsToRevalidate.includes(collection)) return
try {
await fetch(`${process.env.NEXTJS_URL}/api/revalidate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-revalidate-secret': process.env.REVALIDATE_SECRET!,
},
body: JSON.stringify({ collection, keys }),
})
} catch (err) {
console.error('Failed to revalidate cache:', err)
}
})
// ===== NOTIFICATIONS =====
action('items.create', async ({ collection, key, payload }, context) => {
if (collection !== 'contact_submissions') return
// Notify team in Slack
await fetch(process.env.SLACK_WEBHOOK!, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: `📬 New submission from ${payload.name} <${payload.email}>\n${payload.message}`,
}),
})
})
// ===== AUDIT LOG =====
action('items.update', async ({ collection, keys, payload, accountability }) => {
if (!accountability?.user) return
// Log changes to audit_logs collection
const { getSchema } = context as any
const schema = await getSchema()
// ... write to audit_logs
})
// ===== STOCK SYNCHRONIZATION =====
action('items.update', async ({ collection, keys, payload }, context) => {
if (collection !== 'orders') return
if (payload.status !== 'paid') return
const { database } = context as EventContext & { database: any }
const order = await database('orders')
.where({ id: keys[0] })
.first()
if (order?.items) {
const items = JSON.parse(order.items)
for (const item of items) {
await database('products')
.where({ id: item.product_id })
.decrement('stock', item.quantity)
}
}
})
// ===== CRON—daily report =====
schedule('0 9 * * 1-5', async () => {
const response = await fetch(`${process.env.API_URL}/custom/reports/sales`)
const stats = await response.json()
await fetch(process.env.SLACK_WEBHOOK!, {
body: JSON.stringify({
text: `📊 Yesterday's report: orders ${stats.count}, revenue ${stats.revenue.toLocaleString()} ₽`,
}),
})
})
}
function generateSlug(text: string): string {
const translitMap: Record<string, string> = {
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'yo',
ж: 'zh', з: 'z', и: 'i', й: 'y', к: 'k', л: 'l', м: 'm',
н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u',
ф: 'f', х: 'h', ц: 'ts', ч: 'ch', ш: 'sh', щ: 'sch',
ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
}
return text
.toLowerCase()
.replace(/[а-яё]/g, char => translitMap[char] || char)
.replace(/\s+/g, '-')
.replace(/[^\w-]/g, '')
.replace(/-+/g, '-')
.slice(0, 100)
}
Real Case: 1C Integration
For a large e-commerce store, we implemented automatic synchronization of orders and stock via hooks. After payment, a hook sends order data to 1C via REST API, and when stock changes in the external system, it updates Directus. Synchronization time dropped from 15 minutes to 5 seconds. Server load decreased by 40% by eliminating unnecessary API calls. Integration development time was halved compared to the traditional approach. Development cost was $1,200, and the client saved over $3,000 monthly in manual data entry. Contact us to develop custom Directus hooks—starting at $800 per hook.
What's Included, Pricing, and Guarantees
- Source code with TypeScript comments
- Documentation for installation and setup (README)
- Access to a private Git repository
- Team training (1 hour online)
- Support for 2 weeks after delivery
Development of a typical set of 3–5 hooks (validation, notifications, cache) takes 2–5 business days. Costs range from $800 to $2,500 depending on complexity. Timelines are finalized after analyzing your business logic.
Our team has deep expertise in Directus development, having completed 50+ customization projects including integrations with 1C, CRM, and payment systems. We guarantee code quality, deadline adherence, and full support. Get a free consultation with an engineer—we'll answer any questions.







