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

Aperta
#19,717 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@TejasLamba2006 ci sta già lavorando.

Dal 18/11/2026.

  • #19723 di @TejasLamba2006 — aperta

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
Ambito
api, backend

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

area: core Bug Payload OSS
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 items with a required text field title, writable only by users with role writer;
  • a role select (writer / reader) on users;
  • 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

  • addDataAndFileToRequest takes the media type as the part of Content-Type before the first ;, so parameters such as charset are ignored. It assigns req.data only when that media type is exactly the string application/json (case-sensitive comparison), and for multipart/* when _payload is present. Otherwise req.data stays undefined and no error is thrown.
  • The collection REST endpoints (create, updateByID, update) pass data: req.data to the operations.
  • After executeAccess, the field beforeValidate traversal reads siblingData[field.name] (the typeof siblingData[field.name] === 'undefined' check before the fallback value) while siblingData is undefined or null.
  • Phase order (observed at runtime): beforeOperation → access → field beforeValidate (crash here; field-level beforeValidate hooks run after this point) → collection beforeValidate → beforeChange. So an application cannot reject this input with a 4xx in a hook that runs after access control. Throwing in beforeOperation would turn the 403 of unauthorized users into a validation error.
  • The auth endpoints (login, forgotPassword, resetPassword, unlock, registerFirstUser) already read req.data?.field defensively, and duplicate uses data || {}.

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 data that 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.parse of the multipart _payload field in the same utility. Related, but it does not cover a missing or non-object req.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

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di payloadcms/payload

Tutte le issue di payloadcms/payload

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.