Strapi 5 lifecycle hooks and Document Service middlewares

In Strapi 5, database lifecycle hooks are triggered differently by Document Service methods because of Draft & Publish, and Strapi recommends the Document Service for most use cases. This page explains what that means for email and sync logic and how to test it.

On this page

Why Strapi 5 lifecycle hooks behave differently after an upgrade

If your Strapi v4 project uses database lifecycle hooks to send emails or sync data to another system, those hooks will not necessarily fire the same way in Strapi 5. Hooks fire differently in Strapi 5 because of the Draft & Publish model, and Strapi recommends the Document Service for most use cases. Before you upgrade, list every hook in your project and record what it triggers, which content types it runs on, and whether it runs on create, update, publish or delete. That inventory decides which hooks need to move and which can stay. The mechanics of the upgrade itself, including the codemods and the data migration that runs on first start, are covered in the Strapi v4 to v5 migration docs, so this section focuses on the behavior change that affects your business logic.

In Strapi 5, a single save can touch a draft version, a published version or both, and the Document Service methods trigger work at a different level than the older Entity Service calls did. A hook written against a v4 lifecycle event may therefore run more than once, run for the draft and not the published version, or miss a publish action entirely. Move logic into Document Service middlewares when the behavior must hold regardless of which API call or admin action changed the content, such as sending a notification only on publish or syncing a record only when its status changes. Keep a lifecycle hook only when it is a narrow, database-level step that does not depend on the document state, and confirm that choice against the current Strapi breaking change notes on lifecycle hooks.

What changes for Strapi 5 lifecycle hooks

This table compares how lifecycle hook behavior shifts between Strapi v4 and Strapi 5, and what each shift means for code you already run. Read each row as a question to answer in your own project: which API calls reach your hooks, and which states of content they see. Confirm exact hook names and event payloads against the linked Strapi breaking change page before you change code.

ChangeImpact on hooksAction needed
Entity Service replaced by Document ServiceHooks written around Entity Service calls may not fire the same way for equivalent Document Service calls. Confirm this for each method you use.Inventory every hook and every place it is triggered. Map each old call to its Document Service equivalent and test it.
Draft & Publish modelHooks fire differently depending on which Document Service method runs, because drafts and published versions are handled as separate states.For each hook, record whether it should run on draft saves, publishes or both, then verify that behavior in a staging project.
Document Service recommended for most use casesStrapi recommends the Document Service for most work, so new logic is more likely to be written against it than against older database hooks.Write new side-effect logic against Document Service middlewares unless a specific requirement points elsewhere. Record the reason for any exception.
v4 response format headerThe Strapi-Response-Format: v4 header can keep client responses in the older shape, which may hide differences in what your code receives during the switch.Do not rely on the header to validate hook output. Test server-side payloads directly, then remove the header client by client.
Emails and data sync triggered by hooksDuplicate or missed sends and syncs can appear when a hook runs on a draft save, a publish or a both paths.Confirm the triggering method and status for each email or sync job. Test duplicates, retries and unpublish paths before go-live.
Exact hook names and event payloadsNames and payload fields may differ from v4 and determine what your logic can read.Confirm each name and payload field against the Strapi breaking change page for lifecycle hooks and the Document Service before rewriting code.

How Draft & Publish changes which hook fires

In Strapi 5, one API call can fire different lifecycle logic than it did in v4 because the Draft & Publish model stores a draft and a published version as separate states. The Document Service addresses a document as a whole, so a save, a publish and an unpublish can each touch a different row or state, and the hooks attached to the underlying database layer do not always fire the way a v4 developer expects. Strapi's breaking change notes for lifecycle hooks say the triggering differs by Document Service method, and they recommend the Document Service for most use cases. Treat every hook as a question of which state it sees, not just which request it came from.

Start with an inventory of your own code. List every beforeCreate, afterCreate, beforeUpdate, afterUpdate and delete hook, and every custom service call that writes content. For each one, record which Document Service method reaches it (create, update, publish, unpublish, delete) and whether the logic inside assumes a single record. Then compare two cases: a plain save of a draft and a publish action on the same document. If the email, sync or audit logic runs on both, decide whether that is intended. A publish that sends a notification a second time, or a draft save that pushes unpublished content to a downstream system, is the usual failure. The exact firing sequence for each method is something to confirm against the current Strapi documentation for your version.

Verify the behavior on a copy of your own project, not on assumptions from this page. Illustrative example: a team creates a draft, saves an edit, publishes, then unpublishes, while a temporary logging hook records each event and the state it sees. Run the same sequence through the admin panel and through your own API calls, because the two paths can reach the Document Service differently. Keep the log as evidence for the change record, and rerun it after each Strapi minor upgrade, since hook behavior is part of what those upgrades can change.

How a Document Service call reaches the database and hooks

The walk-through starts with an editor or API client calling the Document Service API, which passes the call through the middleware chain before any row is written. From there the request reaches the database layer, where draft and published versions are stored as separate states, and the lifecycle subscribers run. Check which state each hook sees, because a hook that only fires on one branch will miss the other. Email and sync side effects should be traced to the exact branch that triggers them.

Where a Document Service call branches between draft, published and side effects.

When to move Strapi 5 lifecycle hooks into Document Service middlewares

Some logic must run no matter how a record is written: through the admin panel, the REST or GraphQL APIs, a custom controller, a script or the Document Service itself. Audit stamps, ownership checks and derived fields belong here. In Strapi 5, database lifecycle hooks are triggered differently by Document Service API methods because of the Draft & Publish model, so a hook that worked in v4 may fire for some operations and not others. A Document Service middleware is the better fit because it wraps the Document Service calls your code depends on. Keep a hook only when you can show that it fires for every write path you use.

  • Map every entry point: list admin edits, API creates, publish and unpublish actions, imports and scripts that write content.
  • Test publish and draft separately: confirm the logic runs for both draft and published states.
  • Check bulk operations: confirm whether the logic runs once per document or once per locale.
  • Document the exceptions: if a hook stays, record which paths it covers and why.
  • Confirm against the breaking change notes: review Strapi's lifecycle hooks guidance for the methods affected.

Before changing this logic, confirm with an integration test that every write path produces the same stored result.

Risks when hooks send emails or sync data

Lifecycle hooks and middlewares run inside content saves, publishes and deletes, so a side effect added there runs every time that path runs. The cards below cover the failure modes teams most often meet when hooks send email or push data to other systems, each with the symptom to look for and the control that reduces it.

Duplicate emails after a publish

A hook that sends a notification on every update will fire again when an editor saves a draft, republishes or edits a related entry. Under the Draft & Publish model, a single editorial action can touch both the draft and published versions, so one event may look like several. Check which event and which status the hook reads, and confirm that the notification fires once per intended transition, not once per write.

Lifecycle hooks docs

Sync jobs that fire on drafts

A sync to a search index, CRM or storefront that runs on every write can push unpublished draft content to systems that expect only live content. Editors then see work in progress in public or partner-facing channels. Confirm the status the sync reads, test a draft-only save, and make sure unpublish and delete events also reach the target system.

Retries that repeat side effects

When a request fails after a hook has already sent an email or called an external API, a retry from the editor or a client repeats the side effect. Nothing in Strapi tracks whether an outbound call has already succeeded, so the hook needs its own idempotency key or a record of completed sends. Check the behavior by forcing a failure after the external call and retrying the save.

Missed events on bypassed paths

Logic placed in one layer may not run when content changes through another path, such as a bulk import, a data transfer or a direct database write. Teams then see records that never reached the target system. List every entry point that writes content in your project, then test each one against the expected side effect, and document which paths are intentionally silent.

Ordering problems with transactions

A hook that calls an external service before the database transaction commits can send data about a record that is later rolled back. The reverse case also happens when the service reads the record before it is visible. Decide whether each side effect should run before or after the commit, and test failures that occur between the write and the notification.

Hard-coded secrets and endpoints

Email provider keys, webhook URLs and API tokens written directly into hook files tend to survive into repositories, logs and backups. They also make it hard to point staging at a test mailbox instead of a live list. Read credentials from environment configuration, restrict which environments can send, and confirm that a staging deployment cannot reach production endpoints.

How to move a hook into a middleware without losing behavior

This sequence moves logic from a Strapi 4 style lifecycle hook into a Document Service middleware while keeping the same results for editors, end users and downstream systems. It ends with a tested change that can be switched on and off until the new path has passed on a copy of production data.

  1. Inventory every lifecycle subscriber

    List each lifecycle subscriber in the project, including the content type it watches, the events it handles (such as create, update, publish or delete), and what it does, such as sending an email, calling an API or writing a derived field. A developer who knows the codebase should do this, and a second reviewer should check it against the project's source files. The step is done when every subscriber has a row in a shared inventory with its side effects written out, so nothing is removed from the list by accident.

  2. Map each event to Document Service calls

    For each inventory row, identify which Document Service methods (such as create, update, publish, unpublish and delete) call the logic that fires the old hook, and note which of them the application uses. Strapi 5 triggers database lifecycle hooks differently for these methods because of the Draft & Publish model, so a hook that worked on a single entry may not fire on every publish path. The output is a table that links each side effect to the exact methods and editor or API actions that trigger it.

  3. Write the middleware in a branch

    Create a feature branch and implement the middleware in the project's Strapi backend, registering it for the content types and methods mapped in the previous step. Keep the old subscriber in place so the two can be compared. The developer should note any differences in input data, such as documentId usage or the status of the entry, because the middleware receives Document Service arguments rather than the older entity shape. The step is done when the branch builds and the middleware is registered for every mapped method.

  4. Run the same test cases on both paths

    Write test cases that describe the behavior the business expects, such as an email sent once on publish, or a synced record created with the correct identifier. Run them against the old hook on the current v4 behavior, then run the same cases against the new middleware on Strapi 5. Where the expected output differs, decide whether the old behavior was intended before changing the test. The output is a pass or fail report per case, with any unexplained difference logged as an open issue.

  5. Check draft and published paths separately

    Test draft saves, publishing, unpublishing, and deleting as separate scenarios, and confirm that each one triggers the side effect exactly as the business requires. Because Draft & Publish changes how the events fire, a hook that sends an email on publish should be checked for duplicates on repeated saves and for missed sends when content is published through the API. The step is complete when each draft and published scenario has a recorded result and any gap has a fix or a documented decision.

  6. Deploy to staging with a database copy

    Restore a recent copy of the production database into a staging environment that runs the new code, and exercise the editorial and integration flows against it, including emails sent to a test mailbox and any sync targets set to a sandbox. Confirm that the staging system points at non-production email and external endpoints before any test runs. The step is done when staging results match the expected outcomes from the test run, and the team has signed off on the side effects observed.

  7. Keep the old hook behind a flag

    Ship the middleware to production with the old subscriber still in the code and controlled by a configuration flag, so one value enables the old behavior and the other enables the new middleware. Only one path should run at a time to avoid duplicate emails or syncs. Set a rollback point before the production deployment by taking a fresh database backup and recording the release version. Strapi does not support downgrading, so the pre-upgrade database backup remains the restore point if the change must be reversed. Remove the old hook only after the new path has passed in production for a period the team agrees in advance.

Testing hooks that send emails or sync data

Test the hook logic on its own first, then test the wiring. Unit tests should call the middleware or lifecycle function directly with a stubbed email provider and stubbed external APIs, and assert the exact payload sent, the branch taken for each status, and the error path when the provider fails. These tests run in seconds and catch most logic defects, but they cannot show that the hook actually fires during a Document Service call, which is the gap that matters after a Strapi 5 move.

Integration tests should run against a disposable test database and call the Document Service methods your editors use, such as create, update, publish, unpublish and delete. For each action, assert that the side effect happened exactly once: one email, one sync request, one row written to your target system. Cover every path separately, because draft saves, publishes, unpublishes and deletes can trigger different hooks. Confirm that a publish does not also send a draft notification, and that deleting an entry removes or flags its record downstream. For idempotency, replay the same event with the same documentId and confirm the second call changes nothing. Confirm with your own team which test runner and database fixtures fit your stack.

Finish with staging checks against a sandbox mail account and a test sync target that mirrors production configuration, including credentials and webhook URLs kept separate from live values. Run a short script of real editor actions and compare the recipient list and target records with the expected output. Keep a record of the results before go-live, since the Strapi lifecycle hooks breaking change notes are the reference for which triggers changed, and retest after every Strapi minor upgrade.

What makes hook migration take longer

This table lists the factors that expand the work of moving lifecycle hook logic in a Strapi 5 project, why each one adds effort, and how to reduce it. Use it to check whether a quote reflects the actual scope of your hooks before you agree to a fixed-scope plan.

DriverWhy it adds workHow to reduce it
Number of lifecycle subscribersEach subscriber must be traced to the Document Service methods that now trigger it differently, so every subscriber needs review even when its code looks simple.Inventory all subscribers first and tag each one by the content types and operations it handles.
Content types and draft-enabled models touchedDraft & Publish changes which operations fire a hook, so models with draft enabled need separate test cases for create, update, and publish.Limit hooks to the models that truly need them and move shared logic into one service.
External systems called by hooksHooks that send email, push to a CRM, or write to a search index need credentials, sandboxes, and failure handling that a pure database change does not.Route external calls through a queue or service layer with a documented retry policy.
Idempotency of side effectsIf a hook can run twice for one save, duplicate emails or duplicate records can reach production during migration testing.Add idempotency keys or check-before-write logic, and confirm the behavior with the client's team.
Test coverage of existing hooksWithout tests, each hook must be verified by hand against old and new behavior, which expands review time.Write tests that capture current behavior before changing any hook code.
Custom plugins that register hooksPlugins can subscribe to lifecycle events, so their behavior changes too, and their owners may not be the same team as the project.List every plugin that subscribes to events and confirm its compatibility status with the project owner.
Number of environments to checkEach environment (local, staging, production) may hold different data and integrations, so behavior must be confirmed in each one.Agree which environments need verification and what evidence each one produces.
What to ask for in a quoteA scope that omits any of the drivers above is likely to change after work begins.Ask the partner to list each subscriber, external call, plugin hook, and environment in the written scope.

Questions buyers ask about Strapi 5 lifecycle hooks

Can we move lifecycle hooks to Document Service middlewares without a full Strapi 5 upgrade?

Hooks are tied to the Strapi version that runs them, so the move is normally done as part of, or immediately around, a Strapi 5 upgrade rather than on a v4 project on its own. The reason is that Strapi 5 changes how database lifecycle hooks fire for Document Service calls, because of the Draft & Publish model. A hook that works on a v4 project may fire at different points, or not at all, once the project runs on Strapi 5. Confirm with your team which Strapi version each environment runs and whether the hook logic can be tested on a copy of the Strapi 5 build before the cutover. Strapi recommends the Document Service for most use cases, so the target design is usually a Document Service middleware, not a patched hook.

What drives the cost and effort of moving hooks?

The main driver is how many hooks exist and what each one does. Cost comes from four parts: reading the existing hook code and mapping every content type it touches, rewriting the logic as middlewares or service calls, testing each path including draft, publish and bulk operations, and handling side effects such as emails or syncs. Hooks that only set a field are cheap to move. Hooks that send notifications, write to other systems, or depend on publish state need more design and more testing. One-time work covers the rewrite and test plan. Recurring cost appears only if the hooks call external services that change over time and need upkeep. Ask any provider to price the work per hook group, with the test plan included.

How long does the hook work take, and why does the answer depend on the inventory?

Duration cannot be stated responsibly before someone has counted the hooks. A project with a few simple field-setting hooks is a very different job from one with dozens of hooks that send emails, call a CRM and write to a search index. The inventory tells you how many content types are affected, which hooks depend on draft or publish status, which ones have side effects outside Strapi, and which need data fixed in the database. Ask for an inventory as the first deliverable, then ask for a timeline based on that list. A timeline that is quoted before the inventory exists should be treated as a guess.

What do we need to provide for the hook work?

The work needs four things from your side. First, access to the code repository, including every file under the content type and API folders where hooks live, and the Strapi version in use. Second, a recent copy of the database, so that behavior can be checked against real data without touching production. Third, test accounts with the roles that create, edit, publish and unpublish content, so each permission path can be exercised. Fourth, a named sign-off owner who can approve behavior changes, especially for emails and data syncs that customers or staff will notice. Without that owner, decisions about edge cases stall, and the cutover date slips.

Can our in-house team move the hooks themselves?

An in-house team can do the work if it has engineers who know the Strapi codebase, can read the existing hooks, and can write and run automated tests against a copy of the database. The skills that matter most are understanding the Document Service API, reproducing draft and publish flows, and testing side effects. Teams often underestimate the testing part. A realistic self-check is to ask whether the team can run every hook path on a staging copy and confirm that each email or sync fires once, with the right data, and not on draft saves. If that is not clear, a partner can take the design and testing, while your engineers keep ownership of the code.

How should we handle hooks that send email or sync data to third-party systems?

Treat them as the highest-risk part of the move. Map each hook to the event it should react to, such as a publish, an update or a scheduled change, and confirm the new trigger in Strapi 5 before writing code. Then decide what happens on retries and failures, because a middleware that calls an external system can fire more than once or fail halfway. Test in a sandbox mail server or a test instance of the third-party system, and check that draft saves do not send messages to readers. Keep a list of which integrations were live before the cutover so that you can confirm nothing was silently dropped. Record the decisions with the sign-off owner.

Do we need to test hooks differently after the move?

Yes. Unit tests alone are not enough because the behavior depends on the Document Service flow and on the publish state of each entry. Write tests that create, update, publish, unpublish and delete entries through the same service calls your editors and APIs use, then assert on side effects such as sent emails, synced records and changed fields. Run the same tests on v4 behavior and on Strapi 5 to find differences you did not expect. Keep the test suite in your repository so that future Strapi upgrades can rerun it.

How DeployOpen works on this

DeployOpen starts by mapping every existing lifecycle hook and the code paths that call it, then decides which logic belongs in a Document Service middleware and which belongs in a service or job. The work is planned as a fixed-scope engagement inside your own infrastructure, so email and data sync behavior is verified before the hooks are removed.

How we scope

  • Inventory every lifecycle hook, the content types it touches and the Document Service or Entity Service calls that trigger it.
  • Record which hooks send email, call external APIs or write to other systems, since these carry the highest risk on change.
  • Agree in writing which hooks move to middlewares, which are rewritten as services and which are retired, with the test cases for each.

How we build

  • Rewrite selected logic as Document Service middlewares, keeping the order and conditions the original hooks relied on.
  • Handle draft, publish and unpublish events explicitly so side effects do not fire on the wrong status change.
  • Add idempotency keys or guards to email and sync code so repeated or partial triggers do not duplicate actions.

How we hand over

  • Deliver a written map from each original hook to its new location, with the reasoning for each decision.
  • Provide automated tests for email and sync behavior in staging, including the draft and publish paths and failure cases.
  • Document how to add or change a middleware safely, and which hooks, if any, remain in the codebase and why.

How we support

  • Run a retest after each Strapi 5 minor upgrade, since middleware behavior is part of the regression set.
  • Offer ongoing support, upgrades and continuous testing as a retainer after the initial handover.
  • Confirm with your team which environments, secrets and mail or sync accounts the support scope covers before work starts.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.