#5900·undici

HTTP/1.1 304 with Content-Length closes the connection

Author: koal44Created Sep 25, 2026Updated Sep 28, 2026
Labelsbug

A bodyless 304 response with a nonzero Content-Length causes request() to fail with UND_ERR_RES_CONTENT_LENGTH_MISMATCH and closes the connection. Removing the header avoids the failure.

A server is allowed to send a 304 (Not Modified) response with a length describing what the 200 response would have been (see RFC 9110 §8.6, and RFC 9112 §6.3). So the 304 needs an exception from any body-length check.

Here's a failing unit test.

javascript
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { test } from 'node:test';
import { Client } from 'undici';

test('304 with Content-Length', async t => {
  const server = createServer((req, res) => {
    res.writeHead(304, { 'content-length': '123', etag: '"foo"' });
    res.end();
  });
  await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  const client = new Client(`http://127.0.0.1:${server.address().port}`);
  t.after(async () => { await client.destroy(); server.close(); });
  const { statusCode, body } = await client.request({
    path: '/', method: 'GET', headers: { 'if-none-match': '"foo"' },
  });
  assert.equal(statusCode, 304);
  assert.equal(await body.text(), '');
});
> node --test ./undici-304.test.mjs
...
Error [ResponseContentLengthMismatchError]: Response body length does not match content-length header