Skip to content

Content-Length

Description

The Content-Length response header indicates the size of the response body in bytes. This header provides the exact length of the entity being transferred, allowing clients to know how much data to expect and to determine when a complete message has been received.

The Content-Length header plays a crucial role in HTTP message framing, especially in persistent connections (keep-alive) where multiple request-response cycles occur over the same connection. By specifying the exact length of the response body, clients can determine the end of one response and the beginning of the next without relying on connection closure.

This header is typically used with responses that have a fixed-length body, such as static files or predetermined content. For dynamic content where the size is not known in advance, chunked transfer encoding (indicated by the Transfer-Encoding: chunked header) is often used instead.

Syntax

The syntax of the Content-Length header follows this structure:

Content-Length: <length>
  • <length>: A non-negative integer representing the size of the response body in bytes.

Example Syntax

Content-Length: 1234

This example indicates that the response body is 1,234 bytes long.

Examples

Basic Example

A response with a fixed-length body:

HTTP/1.1 200 OK
Date: Mon, 02 Jun 2025 18:00:00 GMT
Content-Type: text/plain
Content-Length: 13

Hello, World!

In this example, the response body is exactly 13 bytes long.

JSON Response Example

A JSON API response with Content-Length:

HTTP/1.1 200 OK
Date: Mon, 02 Jun 2025 18:10:30 GMT
Content-Type: application/json
Content-Length: 57

{"status": "success", "data": {"message": "Hello, World!"}}

Binary Content Example

A response with binary content:

HTTP/1.1 200 OK
Date: Mon, 02 Jun 2025 18:20:45 GMT
Content-Type: image/png
Content-Length: 12345
Cache-Control: max-age=86400

[... 12345 bytes of binary PNG data ...]

Empty Response Example

A response with no body:

HTTP/1.1 204 No Content
Date: Mon, 02 Jun 2025 18:30:15 GMT
Content-Length: 0

In this example, the Content-Length is explicitly set to 0 to indicate that there is no response body.

Summary

The Content-Length response header is a fundamental component of HTTP message framing, providing clients with critical information about the size of the response body. This header enables efficient handling of responses, particularly in persistent connections where multiple request-response cycles occur over the same connection. While not always required (such as when chunked transfer encoding is used), providing an accurate Content-Length header improves client performance and ensures proper message boundary detection. Servers should include this header whenever the exact size of the response body is known in advance.