aldenks
aldenks
CDCloudflare Developers
Created by aldenks on 5/5/2025 in #workers-help
How to stream responses and return a known content length?
An example of the relevant code. I am seeing the X-Content-Length header so I know it's hitting that branch but the Content-Length header is removed (following spec). I do want to follow http spec. I'm wondering if there's a way for workers to send the data along without be buffering in memory and with a content length header? HTTP2+ not having transfer encoding chunked at all seems to suggest there might be a way?
const s3Response = await getS3Object(catalogItem.s3Region, fullS3Url, rangeHeader);

const headers = new Headers({
'Content-Type': 'application/octet-stream',
});

setCacheHeaders(headers, path);

if (s3Response.ContentLength != null) {
headers.set('Content-Length', s3Response.ContentLength.toString());
headers.set('X-Content-Length', s3Response.ContentLength.toString());
}

const response = new Response(s3Response.Body as ReadableStream, {
headers,
status: 200,
});
const s3Response = await getS3Object(catalogItem.s3Region, fullS3Url, rangeHeader);

const headers = new Headers({
'Content-Type': 'application/octet-stream',
});

setCacheHeaders(headers, path);

if (s3Response.ContentLength != null) {
headers.set('Content-Length', s3Response.ContentLength.toString());
headers.set('X-Content-Length', s3Response.ContentLength.toString());
}

const response = new Response(s3Response.Body as ReadableStream, {
headers,
status: 200,
});
2 replies