Skip to content

Commit 4861fa1

Browse files
The MavikAlessioGr
andauthored
fix: return 400 for malformed JSON request bodies (#15706)
Fixes #15635 Wraps `JSON.parse` in `addDataAndFileToRequest` with error handling to return 400 Bad Request for malformed JSON bodies instead of an unhandled 500 Internal Server Error. --------- Co-authored-by: Alessio Gravili <github@gravili.net>
1 parent df17cb1 commit 4861fa1

2 files changed

Lines changed: 19 additions & 5 deletions

File tree

packages/payload/src/utilities/addDataAndFileToRequest.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,18 @@ export const addDataAndFileToRequest: AddDataAndFileToRequest = async (req) => {
1616
const bodyByteSize = parseInt(req.headers.get('Content-Length') || '0', 10)
1717

1818
if (contentType === 'application/json') {
19-
let data = {}
2019
try {
2120
const text = await req.text?.()
22-
data = text ? JSON.parse(text) : {}
23-
} catch (error) {
24-
req.payload.logger.error(error)
25-
} finally {
21+
const data = text ? JSON.parse(text) : {}
2622
req.data = data
2723
// @ts-expect-error attach json method to request
2824
req.json = () => Promise.resolve(data)
25+
} catch (error) {
26+
if (error instanceof SyntaxError) {
27+
throw new APIError('Invalid JSON', 400)
28+
}
29+
req.payload.logger.error(error)
30+
throw error
2931
}
3032
} else if (bodyByteSize && contentType?.includes('multipart/')) {
3133
const { error, fields, files } = await processMultipartFormdata({

test/collections-rest/int.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,18 @@ describe('collections-rest', () => {
5454
expect(doc).toMatchObject(data)
5555
})
5656

57+
it('should return 400 when request body contains malformed JSON', async () => {
58+
const response = await restClient.POST(`/${postsSlug}`, {
59+
body: '{ invalid json',
60+
})
61+
62+
expect(response.status).toEqual(400)
63+
const result: any = await response.json()
64+
65+
expect(result.errors).toBeDefined()
66+
expect(result.errors[0].message).toEqual('Invalid JSON')
67+
})
68+
5769
it('should find', async () => {
5870
const post1 = await createPost()
5971
const post2 = await createPost()

0 commit comments

Comments
 (0)