REST create/update returns 500 (TypeError in field beforeValidate) when req.data is not a JSON object: non-JSON body, missing Content-Type, or JSON null
Maintainers usually reply within 1 day
Assessment
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Newbie friendliness
- 35/100
- Issue type
- Bug
- Clarity
- Clearly specified
- Activity status
- Stale
- Tech stack
- next.js, typescript
Research direction
Start by tracing addDataAndFileToRequest and the collection REST create, updateByID, and update operations described in the issue, then follow the field-level beforeValidate traversal that reads siblingData[field.name]. Check how to reject non-object request data after access control while preserving 403 responses for unauthorized users. Done means these cases return a client error instead of 500 without changing valid JSON or authorization behavior; an open linked pull request already addresses this issue.
Written by the indexing model from the issue text.
Description
Describe the Bug
When a user who is allowed to create or update documents sends a REST request whose body does not end up as a JSON object, Payload responds with HTTP 500. The expected response is a 4xx.
This happens when the media type of the request (the part of the Content-Type header before any ; parameters) is not exactly the string application/json (the comparison is case-sensitive) and the body is not multipart/* with a _payload field. In that case req.data is left undefined. It also happens when the body is the JSON null; then req.data is null.
The create/update operation then crashes during the field-level beforeValidate traversal, after access control:
TypeError: Cannot read properties of undefined (reading 'title')
TypeError: Cannot read properties of null (reading 'title') // body `null`
The response body only contains the generic error message: Something went wrong. with the dev server, An unknown error occurred. in a production build.
This is not the malformed-JSON case. A syntactically invalid JSON body is already rejected with 400 Invalid JSON (see #15635). The problem here is a missing or non-object req.data.
Users without permission still get 403, because access control runs before the crash. In the tests we ran, the failed requests left no persistent database writes, and the failed PATCH did not modify the document. The 500 responses we observed contained no stack trace, and the server kept answering normally afterwards. With Postgres we also checked that no transaction was left open after the error.
Versions tested:
- 3.94.0 (latest stable v3 at the time of testing): reproduced with SQLite, dev server, Next.js 16.4.6.
- 3.90.2: reproduced with SQLite, dev server, Next.js 16.3.3; also reproduced earlier in a separate application on Postgres with a production build.
Other versions have not been tested.
Link to the code that reproduces this issue
https://github.com/mikypot3/payload-rest-non-object-body-repro
Reproduction Steps
The repository is the official blank template (create-payload-app -t blank, SQLite) with:
- one collection
itemswith a requiredtextfieldtitle, writable only by users with rolewriter; - a
roleselect (writer/reader) onusers; - a dependency-free script that sends the requests.
git clone https://github.com/mikypot3/payload-rest-non-object-body-repro
cd payload-rest-non-object-body-repro
corepack [email protected] install --frozen-lockfile
corepack [email protected] repro:setup # writes .env with a random PAYLOAD_SECRET and DATABASE_URL=file:./repro.db
corepack [email protected] repro:dev # next dev on 127.0.0.1:3000
# in a second terminal, with an empty database:
corepack [email protected] repro
The script registers a test writer through /api/users/first-register; the writer then creates a reader. It sends one request per case and prints status, public message, the change in the number of items, and whether the PATCHed document changed. The TypeError appears in the server terminal.
Minimal request:
POST /api/items
Authorization: JWT <token of a user allowed to create>
Content-Type: application/x-www-form-urlencoded
title=example
Results on 3.94.0 (identical on 3.90.2):
| User | Request | Content-Type | Body | Expected | Actual |
|---|---|---|---|---|---|
| writer | POST /api/items |
application/json |
{"title":"valid"} |
201 | 201 |
| writer | POST /api/items |
application/json |
{"title": (malformed) |
400 | 400 Invalid JSON |
| writer | POST /api/items |
application/json |
null |
400 | 500 |
| writer | POST /api/items |
application/x-www-form-urlencoded |
title=example |
4xx | 500 |
| writer | POST /api/items |
text/plain |
title=example |
4xx | 500 |
| writer | POST /api/items |
(none) | {"title":"…"} |
4xx | 500 |
| writer | POST /api/items |
Application/JSON |
{"title":"…"} |
2xx or 4xx | 500 |
| writer | PATCH /api/items/:id |
application/x-www-form-urlencoded |
title=changed |
4xx | 500 (document not modified) |
| writer | PATCH /api/items/:id |
application/json |
{"title":"…"} |
200 | 200 |
| reader | POST /api/items |
application/x-www-form-urlencoded |
title=example |
403 | 403 |
| reader | POST /api/items |
application/json |
{"title":"…"} |
403 | 403 |
| anonymous | POST /api/items |
application/x-www-form-urlencoded |
title=example |
403 | 403 |
In the separate Postgres application (3.90.2), a bulk PATCH /api/<collection>?where=... with such a body returned 400 with the generic Something went wrong., because the per-document error is caught.
Analysis
addDataAndFileToRequesttakes the media type as the part ofContent-Typebefore the first;, so parameters such ascharsetare ignored. It assignsreq.dataonly when that media type is exactly the stringapplication/json(case-sensitive comparison), and formultipart/*when_payloadis present. Otherwisereq.datastaysundefinedand no error is thrown.- The collection REST endpoints (
create,updateByID,update) passdata: req.datato the operations. - After
executeAccess, the fieldbeforeValidatetraversal readssiblingData[field.name](thetypeof siblingData[field.name] === 'undefined'check before the fallback value) whilesiblingDataisundefinedornull. - Phase order (observed at runtime):
beforeOperation→ access → fieldbeforeValidate(crash here; field-levelbeforeValidatehooks run after this point) → collectionbeforeValidate→beforeChange. So an application cannot reject this input with a 4xx in a hook that runs after access control. Throwing inbeforeOperationwould turn the 403 of unauthorized users into a validation error. - The auth endpoints (
login,forgotPassword,resetPassword,unlock,registerFirstUser) already readreq.data?.fielddefensively, andduplicateusesdata || {}.
Expected behavior
A client error instead of 500, for example:
- 415 Unsupported Media Type (or 400) for request bodies in unsupported content types; possibly also case-insensitive media-type matching, since media types are case-insensitive per RFC 9110;
- 400 when a create/update operation receives
datathat is not an object (undefined,null, primitives), checked after access control and before field traversal.
Related
- #15635 (closed): malformed JSON returned 500. Related, but not a duplicate. Malformed JSON now returns 400, while the cases above do not involve a JSON parsing error.
- #17538 (open PR): adds a try/catch around
JSON.parseof the multipart_payloadfield in the same utility. Related, but it does not cover a missing or non-objectreq.data.
Which area(s) are affected?
area: core
Environment Info
Binaries:
Node: 24.22.3
pnpm: 10.34.6 (via corepack)
Relevant Packages:
payload: 3.94.0
next: 16.4.6
@payloadcms/db-sqlite: 3.94.0
@payloadcms/drizzle: 3.94.0
@payloadcms/graphql: 3.94.0
@payloadcms/next/utilities: 3.94.0
@payloadcms/richtext-lexical: 3.94.0
@payloadcms/translations: 3.94.0
@payloadcms/ui/shared: 3.94.0
react: 19.2.9
react-dom: 19.2.9
Operating System:
Platform: win32
Arch: x64
Also reproduced with payload / @payloadcms/* 3.90.2, next 16.3.3 (SQLite) and, earlier, payload 3.90.2 with @payloadcms/db-postgres 3.90.2 and next 16.4.6 (production build).
- Dominant language
- TypeScript
- Stars
- 45.8k
- Forks
- 4.4k
- Avg merge
- 2d 16h
- Merged PRs (30d)
- 251
Getting set up
Starts the project's dev container in your browser, under your own GitHub account.
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from payloadcms/payload
-
db-d1-sqlite: upsert is aliased to updateOne, so payload.kv.set never inserts new keysPossibly taken @pcbeingused333 claimed this today. OpenBug db: d1-sqlite Payload OSS
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
payloadcms/payload#19766 ·
Maintainers usually reply within 1 day
-
Document bar (.doc-controls__content) overflows a 375 px viewport, clips "Created" and fails axe scrollable-region-focusablePossibly taken A pull request linked to this issue is open or already merged. Openarea: ui Bug
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
payloadcms/payload#19690 ·
Maintainers usually reply within 1 day
-
[v4] Blocks thumbnails croped 3:2Possibly taken @samiarif02 claimed this 2 days ago. Openarea: ui Bug Payload OSS status: needs-triage v3
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
payloadcms/payload#19609 ·
Maintainers usually reply within 1 day
-
Scheduled publish jobs are not deleted when their document is deleted (string id in the job, raw id in the cleanup)Possibly taken @volodymyrshk claimed this 10 days ago. Openarea: core Bug db: sqlite
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
payloadcms/payload#19448 ·
Maintainers usually reply within 1 day
-
plugin-multi-tenant: `isGlobal` collections redirect tenant-scoped users to `/admin` since 3.93.0 (GlobalViewRedirect prop-name mismatch)Possibly taken @JarrodMFlesch claimed this 10 days ago. OpenBug plugin: multi-tenant
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
payloadcms/payload#19420 · 1 assignee ·
Maintainers usually reply within 1 day
All issues in payloadcms/payload
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
milind-soni/OpenMausBot#6730 ·
Maintainers usually reply within 1 day
-
`@angular/[email protected]` depends on vulnerable Vite 7.3.7 - GHSA-p4f5-76q4-ffq7 (Critical RCE)Openarea: @angular/build
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
angular/angular-cli#34764 ·
Maintainers usually reply within 1 day
-
status/need-triage
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
google-gemini/gemini-cli#30384 · 1 comment ·
Maintainers usually reply within 1 day
-
P2
Difficulty 1/5 Under an hour Newbie friendliness 84/100
Maintainers usually reply within 1 day
-
area:image documentation good first issue
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Maintainers usually reply within 1 day