As per official RFC 9110...
How Content-Length is CalculatedThe "Content-Length" header field indicates the associated representation's data length as a decimal non-negative integer number of octets. When transferring a representation as content, Content-Length refers specifically to the amount of data enclosed so that it can be used to delimit framing. In other cases, Content-Length indicates the selected representation's current length, which can be used by recipients to estimate transfer time or to compare with previously stored representations.
The value of the Content-Length header is calculated as the number of bytes in the message body. For instance, if the body of an HTTP message contains a JSON object, the Content-Length would be the total number of bytes in that JSON string. In programming, this can be determined using the length property of the content, such as content.length in JavaScript.
How Browsers Use the Content-Length Parameter
Browsers use the Content-Length header to manage the data they receive from servers. Knowing the exact size of the message body helps browsers allocate the right amount of memory and ensure that the entire message has been received before processing it. This is particularly important for handling large files or streaming data, where incomplete data could lead to errors or corrupted files
Is Content-Length Mandatory?
The Content-Length header is not always mandatory. For example, it is not required for HTTP requests that do not have a message body, such as GET requests. Similarly, it is not necessary for responses with no body, like those with a 204 (No Content) status code. However, for requests and responses that do include a body, the Content-Length header is crucial for proper data handling.