Unverified Commit ead10f1f authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix handling for 204 status code with a body (#28479)

This ensures we handle 204 and 304 status codes correctly in API routes.  

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`

Fixes: https://github.com/vercel/next.js/issues/28464
parent f2168554
Invalid API Route Status/Body Response
#### Why This Error Occurred
In one of your API routes a 204 or 304 status code was used as well as sending a response body.
This is invalid as a 204 or 304 status code dictates no response body should be present.
#### Possible Ways to Fix It
Send an empty body when using a 204 or 304 status code or use a different status code while sending a response body.
Before
```js
export default function handler(req, res) {
res.status(204).send('invalid body')
}
```
After
```js
export default function handler(req, res) {
res.status(204).send()
}
```
### Useful Links
- [204 status code documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204)
- [304 status code documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304)
...@@ -454,6 +454,10 @@ ...@@ -454,6 +454,10 @@
{ {
"title": "next-config-error", "title": "next-config-error",
"path": "/errors/next-config-error.md" "path": "/errors/next-config-error.md"
},
{
"title": "invalid-api-status-body",
"path": "/errors/invalid-api-status-body.md"
} }
] ]
} }
......
...@@ -258,6 +258,22 @@ export function sendData( ...@@ -258,6 +258,22 @@ export function sendData(
return return
} }
// strip irrelevant headers/body
if (res.statusCode === 204 || res.statusCode === 304) {
res.removeHeader('Content-Type')
res.removeHeader('Content-Length')
res.removeHeader('Transfer-Encoding')
if (process.env.NODE_ENV === 'development' && body) {
console.warn(
`A body was attempted to be set with a 204 statusCode for ${req.url}, this is invalid and the body was ignored.\n` +
`See more info here https://nextjs.org/docs/messages/invalid-api-status-body`
)
}
res.end()
return
}
const contentType = res.getHeader('Content-Type') const contentType = res.getHeader('Content-Type')
if (body instanceof Stream) { if (body instanceof Stream) {
......
export default function handler(req, res) {
if (req.query.invalid) {
// test the warning when content is added for a 204 response
return res.status(204).json({ hello: 'world' })
}
return res.status(204).send()
}
...@@ -26,6 +26,36 @@ let mode ...@@ -26,6 +26,36 @@ let mode
let app let app
function runTests(dev = false) { function runTests(dev = false) {
it('should handle 204 status correctly', async () => {
const res = await fetchViaHTTP(appPort, '/api/status-204', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(204)
expect(res.headers.get('content-type')).toBe(null)
expect(res.headers.get('content-length')).toBe(null)
expect(res.headers.get('transfer-encoding')).toBe(null)
const stderrIdx = stderr.length
const res2 = await fetchViaHTTP(
appPort,
'/api/status-204',
{ invalid: '1' },
{
redirect: 'manual',
}
)
expect(res2.status).toBe(204)
expect(res2.headers.get('content-type')).toBe(null)
expect(res2.headers.get('content-length')).toBe(null)
expect(res2.headers.get('transfer-encoding')).toBe(null)
if (dev) {
expect(stderr.substr(stderrIdx)).toContain(
'A body was attempted to be set with a 204 statusCode'
)
}
})
it('should render page', async () => { it('should render page', async () => {
const html = await renderViaHTTP(appPort, '/') const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/API - support/) expect(html).toMatch(/API - support/)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment