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
I maintainer di solito rispondono entro 1 giorno
Valutazione
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Idoneità per principianti
- 35/100
- Tipo di issue
- Bug
- Chiarezza
- Specificata chiaramente
- Stato di attività
- Ferma
- Stack tecnologico
- next.js, typescript
Direzione di ricerca
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.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
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).
- Lingua principale
- TypeScript
- Stelle
- 45.8k
- Fork
- 4.4k
- Merge medio
- 2g 16h
- PR unite (30g)
- 251
Preparare l'ambiente
Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.
- Nessun Dockerfile né file Docker Compose
- Ha un modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di payloadcms/payload
-
db-d1-sqlite: upsert is aliased to updateOne, so payload.kv.set never inserts new keysForse già presa @pcbeingused333 l’ha presa 1 giorno fa. ApertaBug db: d1-sqlite Payload OSS
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
payloadcms/payload#19766 ·
I maintainer di solito rispondono entro 1 giorno
-
Document bar (.doc-controls__content) overflows a 375 px viewport, clips "Created" and fails axe scrollable-region-focusableForse già presa Una pull request collegata a questa issue è aperta o già unita. Apertaarea: ui Bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
payloadcms/payload#19690 ·
I maintainer di solito rispondono entro 1 giorno
-
[v4] Blocks thumbnails croped 3:2Forse già presa @samiarif02 l’ha presa 2 giorni fa. Apertaarea: ui Bug Payload OSS status: needs-triage v3
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
payloadcms/payload#19609 ·
I maintainer di solito rispondono entro 1 giorno
-
Scheduled publish jobs are not deleted when their document is deleted (string id in the job, raw id in the cleanup)Forse già presa @volodymyrshk l’ha presa 10 giorni fa. Apertaarea: core Bug db: sqlite
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
payloadcms/payload#19448 ·
I maintainer di solito rispondono entro 1 giorno
-
plugin-multi-tenant: `isGlobal` collections redirect tenant-scoped users to `/admin` since 3.93.0 (GlobalViewRedirect prop-name mismatch)Forse già presa @JarrodMFlesch l’ha presa 11 giorni fa. ApertaBug plugin: multi-tenant
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
payloadcms/payload#19420 · 1 assegnatario ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di payloadcms/payload
Issue simili
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 75/100
milind-soni/OpenMausBot#6730 ·
I maintainer di solito rispondono entro 1 giorno
-
`@angular/[email protected]` depends on vulnerable Vite 7.3.7 - GHSA-p4f5-76q4-ffq7 (Critical RCE)Apertaarea: @angular/build
Difficoltà 2/5 1-3 ore Idoneità per principianti 65/100
angular/angular-cli#34764 ·
I maintainer di solito rispondono entro 1 giorno
-
status/need-triage
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
google-gemini/gemini-cli#30384 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
P2
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 84/100
I maintainer di solito rispondono entro 1 giorno
-
area:image documentation good first issue
Difficoltà 2/5 1-3 ore Idoneità per principianti 68/100
I maintainer di solito rispondono entro 1 giorno