Strapi middlewares: global, route and Document Service

Strapi middlewares decide where shared logic runs for every request, for one route or around content operations. This page explains how to choose the layer, order the pieces and verify the result before go-live.

On this page

Strapi middlewares: where cross-cutting logic runs in your project

When the same logic, such as audit fields, request timing, input checks or side effects after content writes, must apply across many endpoints, the layer you choose depends on which requests or content operations it has to cover. Route-level and global middlewares wrap HTTP requests, so they see traffic regardless of which content type is touched. Document Service middlewares wrap content operations such as create, update and delete, so they run whenever the Document Service is called, including from code paths that never pass through an HTTP route. Settle this decision before writing custom routes or controllers, because it determines whether logic has to be repeated in each handler or can live in one place.

Global middlewares are registered for the whole server and run on every request, which suits concerns like request timing or correlation identifiers. Route middlewares are attached to specific routes in the route configuration, so they fit checks that belong to one endpoint. Document Service middlewares are registered through the Strapi server and receive the content operation and its parameters before and after it runs, which is where audit fields or post-write side effects belong. Confirm the exact registration API and the context object for your Strapi 5 minor version in the Strapi documentation and in your own test project, since the Document Service replaced the Entity Service in v5.

Ordering matters because middlewares run in the sequence they are registered, and a request-level check that runs after a write hook can leave partial data behind. Map each concern to a layer in a short table during design, then test one write from the admin panel and one from the REST API to confirm both paths trigger the expected logic. Note that a Document Service middleware will also fire for writes made by seeds, imports and integrations, which may or may not be intended. Confirm this with your team before the build starts.

Which middleware layer fits each job

This table compares global middlewares, route middlewares and Document Service middlewares on scope, what each one sees, how it is registered, how it affects ordering and how it is tested. Read each row as a question you ask before placing cross-cutting logic. The main takeaway is that the narrower the layer, the easier it is to reason about and test, and the broader the layer, the more requests or content operations it touches.

Decision pointGlobal middlewareRoute middlewareDocument Service middleware
ScopeEvery request that reaches the Strapi server, including core and custom routesOnly the specific route it is attached to in a router fileContent operations such as create, update, delete and find on content types, regardless of which route triggered them
What it seesRaw request and response context, before route-level logic runsRequest context for one endpoint, including its parameters and bodyDocument Service calls, with the action, the content type uid and the parameters passed to the call
How it is registeredDeclared in the project's global middleware configuration, with a name and orderAttached in the route definition as a middlewares array on that routeRegistered through the Document Service middleware hook in server code, confirm exact hook and file location in the Strapi 5 docs for your version
Effect on orderingRuns in a fixed sequence relative to other global middlewares, so a change can affect every routeRuns after global middlewares and before the controller for that route onlyRuns around content operations, so ordering matters when several middlewares wrap the same call
Broad coverage versus targeted logicCovers everything, which suits logging or headers but risks side effects on unrelated routesKeeps logic close to one endpoint, which is easier to review but must be repeated for each routeCatches writes from REST, GraphQL, imports and scripts alike, which suits data rules but can hide surprising side effects
How to testExercise several unrelated routes and confirm the middleware does not change their responsesCall the specific route with and without the middleware condition, using an integration testCall the Document Service directly in a test with a seeded in-memory database and check the stored result
Typical riskSlows every request or breaks an unrelated endpoint after a change in orderDuplicated logic drifts between routes over timeRecursive calls or unexpected writes when a middleware itself calls the Document Service

How global, route and Document Service middlewares differ in practice

Global middlewares run on every request that reaches your Strapi server, route middlewares run only on the routes you attach them to, and Document Service middlewares run around content operations no matter what triggered them. That last point is the one that changes design decisions. A global middleware sees HTTP traffic, a route middleware sees one endpoint, and a Document Service middleware sees the operation itself, whether the call came from a REST request, a GraphQL resolver, a custom controller, a seed script or an import job. Use the first two layers for request concerns such as headers, logging, rate-sensitive checks or access rules tied to a path. Use the third for rules that must hold for the stored content itself, whatever route or script wrote it.

The Document Service layer matters more after the move to Strapi 5 because the Document Service API replaces the Entity Service API. Code that hooked into entity-level behavior has to be rewritten against documents, and that rewrite is a good moment to decide where each rule lives. If a rule such as stamping an owner, normalizing a slug or refusing to delete a published document must apply to imports and background jobs as well as to the public API, a route middleware will miss those paths. Before the upgrade, inventory your existing hooks and middlewares, then assign each one to a layer. Confirm the current middleware and Document Service middleware signatures in the Strapi documentation for the exact version you run, because the API surface has changed between releases.

The Strapi-Response-Format: v4 header is a migration aid, not a permanent contract. It lets existing clients keep receiving v4-shaped responses while you update them, so any middleware that reshapes output should not depend on that header being present. Plan client work to remove the dependency on the header, test each consuming application against Strapi 5 responses, and set a retirement date for the v4 format in your own release plan. Ask your team to list every client that sends the header, since those are the consumers that will break first if the compatibility path is switched off.

How a request passes through Strapi middleware layers

The request starts at the public edge, where an HTTP call reaches the Strapi process. Global middlewares run first, then route middlewares for the matched route. Policies and the authentication context come next, so later layers can read the user, and only an allowed request reaches the controller. The controller's Document Service call is wrapped by Document Service middlewares before it queries the database, which is the second trust boundary. Confirm the exact ordering for your Strapi version before you place logic in any layer, because the sequence can change between releases.

Request path through Strapi layers, with trust boundaries at the edge and the database; confirm order per version.

Setting up and verifying middleware order before go-live

This sequence turns cross-cutting requirements into a documented middleware layout, registered in the intended order and proven by tests and staging logs before production traffic arrives. It gives the team evidence, not assumptions, that a rejected request never reaches content logic and that a write triggers side effects exactly once.

  1. Inventory cross-cutting requirements

    Start by listing every behavior that must apply across many requests or content writes, such as request logging, rate or size checks, audit records, slug generation, timestamps, or publish-time rules. Ask the security and compliance owners which rules are mandatory, and ask the editorial owners which rules affect content operations. Record each requirement with its trigger (an HTTP request, a specific route, or a Document Service action) and its owner. The output is a short table that every later step refers back to, and it is done when each row has a single trigger and a named owner.

  2. Assign each requirement to a layer

    For each row in the inventory, decide whether it belongs in global middleware (every request, including those for the admin panel and plugins), route middleware (one or a small set of routes), or Document Service middleware (create, update, publish and delete operations regardless of which request caused them). Rules that depend on the authenticated user usually need the request context, so check whether they can run at the route layer. Mark any requirement that would fire on both a request and a background write, because those need the Document Service layer. The check is that every requirement has exactly one assigned layer and a written reason.

  3. Write each middleware with one responsibility

    Create one middleware file per requirement, with a clear name that states its job, such as one that rejects oversized payloads or one that stamps an audit field. Keep business decisions in services and keep the middleware thin, so a reviewer can read it and state what it does in one sentence. Avoid middleware that both authorizes and modifies data, since a failure in one part then hides the other. Store the files under your project's source tree and track them in version control so changes go through review. Done means each file has a single purpose and a reviewer has signed off on its scope.

  4. Register middlewares in the intended order

    Register each middleware in the configuration location that matches its layer, and write down the order in which they run. Global middleware is registered in the project's server configuration, and route middleware is referenced from the route definition itself. Confirm the order in the Strapi documentation for your installed version, and state the order in a comment or in a README next to the registration, because the resulting chain is the thing auditors and new engineers will ask about. Keep the number of global middlewares small so that ordering stays understandable. The check is that a reader can list the full chain for one sample request and get the same answer as the config file.

  5. Write tests with known requests

    Build a small set of test requests with fixed inputs and expected outcomes. Include at least one request that a global middleware must reject before the controller runs, such as an oversized body or a missing required header, and assert on the status code and on the absence of any database write. Include one authenticated request that a route middleware must allow or deny for a specific role. For Document Service middleware, create, update and publish a test entry through the Document Service and assert that the side effect (for example, an audit record) appears exactly once per operation. Run these tests against an isolated test database, as described in your test setup, so results are repeatable.

  6. Confirm order and single execution in staging

    Deploy the same build to a staging environment that resembles production, then send the known requests from the test suite and read the application logs. Each middleware that logs an entry or exit should appear in the order the registration specifies, and each Document Service side effect should appear once per content operation, not once per retry or per related update. If a Document Service middleware fires on nested or related writes that you did not intend, narrow its condition and repeat the test. Save the log excerpts with the test run as evidence for the release record.

  7. Record the chain and gate the release

    Write a short order record that lists each layer, middleware name, responsibility, owner and the test that proves its behavior, and store it beside the code. Ask a second engineer to replay the staging requests from the record without help, and resolve any mismatch between the record and the logs. Make the passing test suite and the staging log review a release gate in your CI and deployment process, so that any later change to middleware order must update the record and rerun the checks. The output is a signed-off chain that an auditor or a new maintainer can verify without reading the whole codebase.

Security risks in middleware: auth bypass, data leaks and silent failures

Middleware sits in front of, or around, every request, so a small mistake in its order, scope or error handling can affect many endpoints at once. The cards below cover the risks we see most often in Strapi projects, each with the control to review and what the project team should confirm before go-live.

Middleware that runs too late

Strapi runs a route's policies and middlewares in a defined order, and a global middleware that sets or checks a value after the controller has already read it protects nothing. Review each custom middleware's position in the chain and confirm that any check on identity, ownership or input runs before the controller and before the Document Service call it protects. Test the route with an unauthenticated request and with a user who lacks the right role.

Strapi 5 docs

Error handling that leaks details

A catch-all error middleware that returns the raw error object can expose stack traces, SQL fragments, file paths or the fields of a record that a request should not see. Review every error path in custom middlewares, confirm that production responses carry only a status and a safe message, and check that logs for these errors do not echo the full request body. Trigger a deliberate failure in a staging environment and read the response.

Global layer changing public endpoints

A middleware registered globally runs on core content routes, admin routes and plugin routes alike, so a change written for one collection can alter the response of a public endpoint without anyone intending it. Confirm which routes each global middleware matches, and whether it is scoped by path, method or content type. List the public endpoints before and after the change and compare the responses for an anonymous request.

Sensitive values written to logs

Middlewares often log request bodies, headers or query strings for debugging, and those can contain passwords, reset tokens, API keys or personal data. Confirm that no custom middleware logs the Authorization header, cookies or full bodies on user and auth routes, and that log levels in production do not enable debug output. Check the log destination and retention with the team that owns it.

Added latency on every request

A middleware that queries the database, calls an external identity or pricing service, or runs a heavy computation on each request adds that cost to every call that matches it. Measure response time for the most-used endpoints with and without the middleware under a realistic load test, and confirm which work can be cached or moved to the route where it is needed. Ask whether the latency budget for the project is documented.

Drift during Strapi upgrades

Middlewares that wrap internal Strapi behavior, such as a Document Service call or a response shape, can break silently when Strapi internals change during an upgrade. Keep a list of every custom middleware with the Strapi internals it depends on, run the project's tests against each new minor release, and review the release notes before upgrading. Confirm who owns that list after the initial build.

Why middleware order decides security and data outcomes

Where a middleware sits in the chain decides what it sees and what it can change. A logging middleware placed before sanitization may record raw request payloads, including fields that should never reach a log file. An audit middleware placed where a failed write throws before it runs records nothing, so the gap stays silent until someone looks for the entry. Both problems pass a basic smoke test, because the request still succeeds. Before go-live, decide the intended position of each cross-cutting concern, such as input cleaning, authorization checks, logging and audit, then confirm the resulting sequence by sending a request that is expected to fail and checking what was written.

Global and route middlewares run on HTTP requests, but Document Service middlewares run on content operations wherever they originate. That distinction matters for imports, seeding scripts and integrations that call the Document Service directly, since they may skip the request path entirely. A rule that rejects or stamps records in a route middleware will not fire during a bulk load, while a Document Service middleware may fire on a load you expected to bypass. For each rule, list every entry point that can write content (admin panel, public and authenticated APIs, custom endpoints, scripts and plugins) and confirm which layer sees each one. Run a seed script against a staging copy and compare the result with the same change made through the admin panel.

Record the intended order in two places: as comments beside the middleware registration in the project configuration, and in the team runbook with the reason for each position. Treat any change to that order as a change that needs review. Plugins are the common surprise, because a plugin may register middlewares of its own, and those can run before or after your code. Review the chain whenever a plugin is added, upgraded or removed, and check the resolved order in the Strapi version you run, since the configuration file alone may not show plugin entries. Confirm the exact ordering behavior for your version in the Strapi documentation before you write the runbook.

Choosing a middleware layer by situation

Global middlewares run for every request that reaches the Strapi server, including core, custom and plugin routes. Use them for checks that must never be skipped, such as request correlation, header policy and body size limits. Because they see the request before route code runs, they should stay free of content-type logic.

  • Request correlation: attach a request ID and pass it into logs so a failed call can be traced across services.
  • Header and size guards: reject oversized bodies or disallowed headers before route code parses input.
  • Content-agnostic logic: keep these checks independent of content types, since they only see the request.
  • Ordering: entries in config/middlewares.ts run in sequence, so place security checks deliberately and confirm where Strapi's default entries sit.
  • Blast radius: a fault here affects admin and plugin routes too, and every call pays the added latency.

Before release, confirm the middleware order in your configuration matches the order you tested, and that the test covers both a core route and a custom route.

Limits to confirm in your Strapi version and environment

Middleware behavior depends on the exact Strapi 5 release, the Node.js runtime, the database driver and where the project is hosted. The cards below list the limits to verify in your own environment before you place cross-cutting logic in a global, route or Document Service middleware.

Strapi 5 version and Node.js runtime

Middleware APIs and their hook points can change between Strapi 5 minor releases, which ship frequently. Pin the exact version your project runs and read the release notes for the version you upgrade to. Strapi 5 runs only on Active or Maintenance LTS Node.js versions, so confirm the runtime your build and production hosts use is on that list. Ask your platform team to record both versions in the project's README.

Strapi releases

Supported database versions

Document Service middlewares run on top of the database layer, so the database engine and version determine which query behavior you can rely on in tests and production. Strapi 5 supports PostgreSQL, MySQL, MariaDB and SQLite at specific minimum versions and does not support MongoDB or other NoSQL databases. Confirm your production engine and version against the installation requirements before writing middleware that depends on transactional behavior.

Minimum PostgreSQL
PostgreSQL 14
Installation requirements

Admin panel traffic coverage

Global and route middlewares apply to specific request paths, and admin panel requests may or may not pass through the same chain as public API calls. Admin login, content manager saves and the Content-Manager routes can behave differently from REST calls made by your front end. Test an editor saving an entry in the admin panel and confirm whether your middleware runs. Have a Strapi developer verify this by logging inside a test middleware before relying on it for authorization or audit logic.

Self-hosted versus Strapi Cloud behavior

Middleware code runs inside your project, but the hosting model affects the surrounding environment: process managers, reverse proxies, load balancers, file storage and the set of plugins and settings you can change. Strapi Cloud also has its own plan limits and backup behavior. Confirm which environment variables, custom server configuration and dependencies your middleware needs are available on the target host. Ask the hosting owner to test a staging deployment on the exact target platform.

Strapi Cloud plans

Document Service coverage on every write path

Document Service middlewares are meant to wrap content operations, but not every code path that writes data may call them in every version. Imports, bulk operations, scheduled jobs, plugin writes and direct database queries can bypass the expected hook. Before relying on a Document Service middleware for validation, audit logging or derived fields, list every write path in your project and test each one. Make the write-path inventory a required sign-off item for the build team.

Middleware order after upgrades

Execution order between global, route and Document Service middlewares can shift when plugins are added or Strapi is upgraded. A change in order can silently alter which logic runs first, for example a transform before a permission check. Record the expected order in a test suite and rerun it after each minor upgrade. Ask the team to treat any order change in a release as a regression to investigate, not as a cosmetic change.

What middleware work costs and what it needs from your team

How much effort does a Strapi middleware layer take to build?

Effort depends on how many cross-cutting rules you need and how many of them touch content operations. A small layer that adds a request ID, a logging hook and one or two route middlewares is a short, contained task. A layer that enforces audit trails, field-level rules and publishing checks across several content types takes longer because each rule needs its order defined, its failure behavior specified and its tests written. No public effort figure applies to your project, so ask for an estimate that lists each rule, the content types it touches and the test cases it needs, and treat any number without that breakdown as unverified.

What raises or lowers the cost of middleware work?

Four factors move the cost most:

  • The number of cross-cutting rules and how many content types or routes each one covers.
  • Plugin interactions, since Users & Permissions, upload, i18n or review features may run their own hooks that your middleware must not break.
  • Audit depth, meaning whether you need a full record of who changed what and when, or only operational logs.
  • Test coverage, meaning whether you need automated tests for ordering and failure cases or only manual checks on staging.

A narrow rule set with clear ownership and existing tests costs less to extend than a broad set that nobody documented.

Which middleware costs are one-time and which recur through Strapi upgrades?

The initial design, build and test work is one-time. Recurring costs come from keeping the layer working as Strapi changes. Strapi 5 minor releases ship frequently, so you should expect to re-run your middleware tests on each upgrade you adopt, and any move between Strapi major versions requires review of how Document Service calls and request handling behave. Ongoing support can be handled by your team or through a retainer, and the choice affects the recurring cost. Ask any quote to separate the build, the test suite and the upgrade checks into their own lines.

Can an in-house team build a middleware layer alone?

Yes, if the team already knows Node.js, Strapi's server structure and the database your project uses. The main risks for an internal team are rule ordering, unintended side effects on Document Service operations and tests that only cover the happy path. Before deciding, check whether the people who will maintain the layer have time to read the Strapi documentation for the exact version you run, write tests against an in-memory database and review each Strapi upgrade. If one of those is missing, a partner can cover the gap for the build, the handover or both.

What does the work need from our team?

Plan to provide repository access, a staging environment that matches production as closely as practical, and a set of sample requests that represent real editorial and API traffic. You should also name a decision owner who can confirm which rules are mandatory, who approves changes to ordering and who signs off on audit requirements. Ask the partner to list these inputs in writing before work starts, so you can confirm access and environments early and avoid waiting during the build.

How does the duration of middleware work follow from the scope?

Duration follows from the written scope rather than from a general rule. Each middleware scope item, such as a global rule, a route-level rule or a Document Service hook, has its own design, build, test and review steps. Once the list of rules, affected content types and required tests is agreed, the duration can be planned around those items. DeployOpen does not publish a price list and does not quote fixed figures in advance. A quote follows the agreed scope, so changes to rules or audit depth change the schedule and the cost together.

Does DeployOpen publish prices for middleware work?

No. DeployOpen does not publish a price list for Strapi work. Most engagements are fixed-scope, with the scope, deliverables and timeline agreed in writing before work starts. To get a quote, send the list of cross-cutting rules, the content types and routes they touch, the plugins in use, your audit and test requirements and your Strapi version. The quote will follow from that written scope, and the scope document should show which costs are one-time and which are ongoing support.

How DeployOpen scopes and tests Strapi middleware work

DeployOpen treats Strapi middlewares as part of the platform's request path, so we map which logic belongs in global, route or Document Service layers before writing code. Each engagement is agreed in writing, and the work is delivered inside infrastructure you control.

How we scope

  • We inventory cross-cutting logic such as logging, audit fields, rate handling and content side effects before choosing a middleware layer.
  • The written scope names each global, route and Document Service middleware, the content types affected and the order they must run in.
  • Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts, and ongoing support is available as a retainer.

How we build

  • We implement middlewares in your Strapi project with explicit ordering, so global and route logic do not run in an undocumented sequence.
  • Document Service middlewares are written to handle create, update and delete operations with the same content rules your editors rely on.
  • We test each middleware against authenticated and unauthenticated requests, including error paths, before it reaches a shared environment.

How we hand over

  • You receive the source code, a map of middleware order and the content operations each middleware covers.
  • Runbooks describe how to add a middleware safely, how to disable one during an incident and what logs to check.
  • Verification notes list the test cases run and any behavior we recommend you confirm in your own environment.

How we support

  • After handover, we can review changes to middleware order when Strapi is upgraded or new plugins are added.
  • Retainers can cover regression testing of middleware behavior against each Strapi 5 release you adopt.
  • Ask for the support scope, response expectations and upgrade approach in the written quote before work begins.

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.