Why Strapi input validation and sanitization in controllers needs its own design
When your team adds custom routes and controllers to Strapi, the first question is what the core still does for you and what your code now owns. Strapi's default content API applies request validation to bodies and query parameters, and it sanitizes output so that fields a caller is not permitted to read are removed from responses. Those defaults depend on the content type schema, the route configuration and the permissions granted to the caller. Once a custom controller reads ctx.request.body directly, calls a service that writes to the database, or returns a hand-built object, the framework's checks may no longer sit on that path. Treat the default behavior as a baseline to verify, not a guarantee to assume.
The responsibility shifts to your code at the point where the controller accepts input the core never sees or returns data the core never shaped. That includes custom fields, multi-step writes, aggregated responses and any call that accepts a populate parameter, since related records can carry fields that the caller's role should not reach. This section sets out the boundary, and the rest of the page works through each control in turn: default validation, custom validation in controllers, output sanitization and relation exposure. Strapi 5 changed the internal API from the Entity Service to the Document Service and changed the response format, so the details that matter for your version should be checked against the current Strapi documentation before you write code. Confirm the behavior on your own project with test requests, not only from the docs or from this page.
Which validation layer handles which risk
Core routes generated for each content type are the layer where Strapi does the most work for you. Requests to find, findOne, create and update pass through validation against the content type schema, and responses pass through sanitization that follows the calling role's permissions. Strapi checks field types, required fields and uniqueness, and it limits filters, sort and populate to fields the role can read. These checks cover the generated paths only, so any logic you place around them is outside their reach.
- Schema validation: field types, required flags, length limits and unique fields come from the content type definition.
- Permission-aware output: fields and relations the public or authenticated role cannot read are removed from responses.
- Query restriction: filters, sort and populate are limited to what the role may access, so hidden attributes stay out of queries.
- Relation exposure: populate can still reach related types that the role is allowed to read, which may include internal records.
- Missed risk: broad permissions on a type that holds internal fields, such as cost figures or reviewer notes, expose those fields to anyone the role allows. Schema checks do not decide which fields should be public.
For each content type, review the public and authenticated permission settings, then send test requests with a non-admin token to confirm which fields and relations come back.
A custom controller reads ctx.request.body and calls the Document Service directly, so the generated checks do not run on that path unless your code invokes them. The team must call the validation and sanitization helpers on the content API before any write, and sanitize the result before returning it. The exact helper names and signatures depend on your Strapi 5 version, so confirm them against the version you run before you build on them.
- Input validation: call the validation helper for the content type on the request body before any Document Service call, since schema errors appear only when you make that call.
- Input sanitization: remove fields the calling role cannot write, so a body value such as
publishedAtor an ownership relation is not set by accident. - Output sanitization: run output sanitization on returned documents, because the Document Service returns the full record.
- Explicit write objects: build the write object from a named list of fields and avoid spreading the request body into the call.
- Missed risk: a custom update that spreads the body lets callers set ownership, status or role fields, a common route to privilege escalation.
Write tests that send forbidden fields, unknown keys and populate values, and confirm that each one is rejected or dropped before any record changes.
Custom routes that accept free-form payloads have no content type schema behind them. Strapi does not infer types, required fields or allowed keys from the request, so the handler receives ctx.request.body and ctx.query as sent. Every check on these routes is one the team writes, and a gap in any of them reaches the data layer directly.
- No automatic checks: nothing confirms field types, lengths or required values unless the route defines them.
- Query operators: pass-through filters can accept operators the API never intended, which can expose records or trigger expensive queries.
- Populate pass-through: a populate value taken from the query can reach relations the caller should not read.
- Explicit schemas: define a validation schema for each route and reject unknown keys, so new fields do not reach the database unreviewed.
- Missed risk: injected query conditions, mass assignment and reads of related records through populate are the usual outcomes when these routes are missed.
Keep an inventory of every custom route with its accepted fields, filter operators and populate allow list, then test each route with malformed payloads, extra fields and nested relation requests.
Which validation and sanitization options fit which controller pattern
This table compares the four ways to validate and sanitize input in a Strapi controller, showing when each fits, what it costs to maintain and where it fails when misused. Read each row against the controller you are writing, and treat the risk column as the check to run during review.
| Option | When it fits | Maintenance cost and misuse risk |
|---|---|---|
| Core schema validation | Standard content type CRUD where field types, required flags and unique constraints describe the rules | Low maintenance because rules live in the content type schema. Misuse risk is assuming it covers business rules such as ownership or state transitions, which it does not. |
| Sanitize and validate helpers from the content API | Custom controllers that accept request bodies or queries and should apply the same rules as core routes | Moderate maintenance because helpers must be called on every custom path. Misuse risk is skipping the call in one branch, which lets raw input reach the Document Service. |
| Explicit schema checks with a validation library | Custom payloads that do not map to one content type, such as multi-step imports or integration callbacks | Higher maintenance because schemas duplicate content type definitions and must change with them. Misuse risk is drift between the library schema and the content type, causing silent acceptance of new fields. |
| Allowed-key lists | Writes where only a few fields may be set by the caller, such as profile updates or status fields | Low to moderate maintenance because the list is short and explicit. Misuse risk is an incomplete list, or copying the whole request body into the update call. |
| Output filtering on populate | Responses that embed relations or components from content types with private fields | Moderate maintenance because each populate path needs review. Misuse risk is a deep populate exposing fields that the public role should never read. |
How to add validation and sanitization to a custom Strapi controller
This sequence takes a custom Strapi controller from unchecked input to one that validates every request, limits what it reads and returns, and is covered by tests for bad and oversized payloads. Each step ends with a check you can run before the change reaches production.
Inventory custom routes and their inputs
List every custom route in your project, its HTTP method, the controller action behind it, and every place the action reads input: request body, query string, route parameters, headers and uploaded files. Record which of those inputs reach a Document Service call or a database query. Owner: the developer who wrote the route, reviewed by a security engineer. Done when the inventory covers every custom route in the project and no action reads
ctx.request.bodyorctx.querywithout an entry in the list.Map each input to a schema
For each input in the inventory, decide the content type or payload shape it must match. Write down the allowed fields, their types, required and optional status, maximum lengths and allowed values, and mark any field that should never be writable from the request, such as ownership, status or role fields. Keep the map in the repository next to the controller so reviewers can compare it with the code. Done when every input has a written schema and every writable field is justified.
Validate the request before any Document Service call
Add validation at the top of each controller action, before any call to the Document Service API or
strapi.db. Reject unknown fields, enforce the types and limits from the schema, and return a 400 response that names the failing field without echoing internal details. Keep business rules in a service so the controller only checks shape. Done when a request with an unknown field or a wrong type returns a 400 response, and a server log entry shows that no write was attempted.Sanitize the query and the output
Sanitize incoming query parameters so filters, sort and pagination can only use the fields and operators the route supports. Then sanitize the response so fields marked private or not meant for the caller are removed before the data leaves the controller. Strapi's sanitize helpers can be used for this, but confirm the exact helper names and behavior against the Strapi version in your project. Done when a query on a disallowed field is rejected or ignored, and a test response contains none of the private fields.
Restrict populate to an allowlist
Replace any open-ended
populatevalue with an explicit allowlist of relations and components the route may return. Reject or drop requests that ask for relations outside the list, because a populated relation can expose fields from another content type that the route never intended to share. Check each populated relation against the same field-level rules you applied to the main type. Done when a request that populates a relation not on the allowlist does not return that relation's data.Test invalid and oversized payloads
Write automated tests that send valid requests, requests with unknown fields, wrong types, missing required fields, values over the length limit, unexpected query operators, and a body larger than your accepted size. Assert the status code, the error shape and that no record changed in the database. Run the suite locally and in CI before each deployment. Done when every rejected case returns the expected error, the database state is unchanged after each rejected case, and the suite passes in CI.
Confirm the field-level result on a live build
Deploy the change to a staging environment that matches production configuration, then send a set of crafted requests from the inventory, including attempts to write protected fields and to populate restricted relations. Check that protected fields are not stored, that restricted data is absent from responses, and that the error messages do not reveal schema details. Record the results with the test run in your change record. Done when staging results match the schema map with no unexpected field in any response.
How populate exposes fields you meant to hide
A correct top-level response does not prove that a route exposes only what you intended. In Strapi, a populate parameter, or a relation or component pulled in by a custom controller, can return fields, related entries and components that sit one or more levels below the route you reviewed. The outer object can look right while nested objects carry data from content types the route was never designed to serve. This is the case even when your controller sanitizes the top-level entry, because the sanitization step you wrote may not cover the related records that the query loads.
Permissions on the related content type matter as much as permissions on the route. A custom controller often calls the Document Service or the database layer directly, and the permission checks that protect a core route may not run on the nested reads your code triggers. The related type's public or authenticated permissions, its private fields and any relations it holds back to other types all determine what can come back. Treat each relation the route can reach as its own exposure point: list the content types reachable from the route, the fields on each, and the roles that can read them, then decide which of those reads the route should allow at all.
Behavior in this area depends on the Strapi version, the populate syntax your code uses and how your controller calls the Document Service, so do not rely on memory or on this summary. Build a test environment with the same Strapi version and a copy of the content model, then request each populated route as an anonymous user and as each authenticated role, and compare the JSON against your intended output. Check the relevant behavior in the official Strapi documentation for your version, and record the result for each relation so a later schema change or upgrade can be retested against the same list.
How a request moves through validation, the controller and sanitized output
A request enters through the Strapi route, then passes route-level permission and policy checks before any body or query validation runs. Invalid input is rejected at the validation step with an error and never reaches the controller. Valid input goes to the controller, which calls the Document Service, and the response is sanitized before it leaves the API. Check that each custom controller both validates its input and sanitizes its output, since Strapi does not do both for code you write.
Request path from the client through validation and the controller to sanitized output.
Security risks to review before go-live
Most input validation failures in Strapi custom controllers come from one gap: the code accepts more data, returns more data, or answers more requests than the content model intended. The six cards below name each exposure and the control to check before production traffic reaches the API.
Mass assignment through body fields
A controller that passes ctx.request.body straight into a Document Service call lets a client set fields the form never shows, such as an owner reference, a publication state or a role relation. Check that every write goes through an explicit allow-list of fields, that server-controlled fields are set in the service layer, and that a test sends extra keys and confirms they are ignored or rejected. Illustrative example: a caller adds an owner field to a profile update and the record changes owner.
Populate leaking related data
Populate expands relations, and a relation can point to a type with fields or entries the caller should never see. The default sanitized output does not replace an explicit decision about which relations and fields a custom route returns. Check each populate path against the public read model, confirm that draft or unpublished related entries are excluded, and test the endpoint as an unauthenticated user and as a standard role.
Query filters exposing private records
Filters, sort and pagination accept client input, so a caller can probe fields by filtering on them or page through records that belong to other users. Custom controllers often merge query parameters into a database query without re-applying ownership. Check that the server adds mandatory filters for ownership and status, restricts which fields may be filtered or sorted, and that a test with another user's identifier returns nothing.
Error messages revealing internal structure
Validation errors, stack traces and database messages can name tables, columns, relation keys and internal IDs, which helps an attacker map the schema. Return a generic message with a stable error code to the client and keep details in server logs. Check how the controller handles thrown errors from the Document Service, whether non-production settings are enabled in production, and what a malformed request returns.
Public permissions on custom routes
A new custom route inherits whatever permissions the role grants, and a public role often gets access by default during development. Confirm that each custom endpoint has an explicit permission for each role, that the public role has no write access unless the design requires it, and that policies run on the route. Compare the exported permissions against the intended access matrix before each release.
Missing rate limits on expensive queries
Deep populate, broad filters and search endpoints can hold database connections far longer than a simple read, and an unauthenticated caller can repeat them. Rate limiting and request size limits protect these routes from accidental and deliberate overload. Check which custom routes are reachable without login, set limits on the expensive ones, and load test the worst-case query the route allows, confirming the database stays responsive.
Questions teams ask before adding validation to Strapi controllers
How much effort does adding validation to Strapi controllers take?
Effort depends mostly on how many routes accept input, how many content types and components each route writes to, and how much custom logic already sits in controllers and services. Routes that only read public content need less work than routes that create or update entries, accept file uploads, or trigger side effects such as emails or webhooks. Teams with a clear route inventory and existing tests usually see a shorter review. The cost components are internal staff time, any partner time under a written scope, and test environment work. Ask any provider to break the quote down by route group and to state which routes are included.
Can an in-house team add validation to Strapi controllers?
An in-house team can do this if it already works with Node.js, Strapi's controller and service layers, and its own content model. The harder part is knowing how request data reaches the Document Service, which fields a given role can read after a write, and how populate changes what leaves the API. Teams without that experience often fix the visible input checks and miss output paths. A practical test is whether the team can explain, for each write route, what is validated, what is sanitized, and which fields come back to each role. If that answer is unclear, a short external review can build the missing knowledge.
What does the validation work need from our team?
The work needs access to the Strapi repository, a staging environment that matches production, and a current list of routes, schemas, roles and public permissions. It also needs sample requests for each route, including valid and invalid payloads, and a named owner who can decide field rules such as length limits, allowed values and required relations. Editors or business owners should confirm which fields are required for publishing. Finally, the team should provide a test database or fixtures so changes can be checked without touching live content. Missing inputs usually add time to the review.
How long does a validation review take for a large number of routes?
Review time grows with the number of routes, but the number alone does not set the duration. The main drivers are how many routes write data, how many share the same service logic, whether custom plugins add their own endpoints, and whether the team has tests that can be extended. A route inventory at the start is the best way to estimate time. Ask for the schedule to be written into the scope with the route groups listed, so changes in route count are visible and priced against the agreed plan.
Does upgrading to Strapi 5 change how validation behaves?
Yes, the upgrade can change behavior that validation depends on. Strapi 5 replaces the Entity Service API with the Document Service API and changes the API response format. The migration documentation provides a Strapi-Response-Format: v4 header for backward compatibility during migration. Controllers that call the older service layer will need rewriting, so their validation and sanitization calls need to be checked again. Do not assume existing behavior carries over. Read the Strapi v4 to v5 migration introduction and FAQ, back up the database first, and rerun the validation tests on the upgraded code.
Does input validation alone stop data leaks through populate?
No. Input validation governs what enters the API, while populate determines what leaves it. A request can pass every input check and still return related content, private fields or relations that the caller should not see. Review each populate path for each role, restrict the fields returned to public or authenticated users, and test responses with real permission sets. Confirm how sanitization handles nested relations in the Strapi version you run. This output review is often the step teams skip, so it should be part of the written scope.
What does a DeployOpen validation scope cover?
A DeployOpen scope is agreed in writing before work starts and is usually fixed for its defined deliverables. It can cover a route inventory, input validation rules for write routes, sanitization of output and populate paths, role-based response checks, tests that run against an in-memory or staging Strapi, and documentation the internal team can maintain. DeployOpen implements this in your own infrastructure. It does not issue audit reports or certifications, so any compliance evidence comes from your own assessor. Ask for the list of routes, the test approach and the handoff format in the written scope.
How DeployOpen scopes and delivers Strapi validation work
DeployOpen treats input validation and sanitization in Strapi controllers as a scoped engineering task with written deliverables. We review the controllers and routes in your project, build the validation and output rules they need, and test the result against the requests your API actually receives.
How we scope
- We list every custom route, controller and service that accepts input or returns Strapi content.
- The written scope names which endpoints, populate paths and query parameters are covered.
- We agree the test environments, data sets and access needed before work begins.
How we build
- We write request schemas for custom endpoints and wrap them in controller-level checks.
- We restrict populate and field selection so responses expose only the fields each role needs.
- We test invalid, oversized and unexpected payloads against both public and authenticated roles.
How we hand over
- You receive the validation rules, output allowlists and test cases as versioned code in your repository.
- A written note records each endpoint, its accepted input, its returned fields and known limits.
- We walk your developers through the rules so future controller changes follow the same pattern.
How we support
- Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
- Ongoing support, Strapi upgrades and continuous testing are available as a retainer.
- After a Strapi 5 upgrade or a new content type, we can retest affected endpoints for the same issues.

