gzip compression with Lambda function URL?

0

Hi

Is there a way to enable gzip compression with the lambda function url, I have set the following in the actual function code but it doesnt seem to work? let response = { statusCode: 200, headers: { 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Origin': '*', 'Accept-Encoding': 'gzip' }, body: JSON.stringify(responseBody) };

2 Answers
0

What are you trying to do? Send compressed content to the function or receive compressed content from the function? In either case, the content is binary, so it will be base64 encoded.

If you want to return from the function to the client, you need to compress the body yourself, encode it using base64, and set the content-type appropriately.

AWS
EXPERT
answered 3 years ago
EXPERT
reviewed a year ago
0

This is doable in function urls, but you can't encapsulate the response inside a JSON structured response. Just send the raw binary as response.

# Convert data to JSON string
json_data = json.dumps(data)

# Compress using gzip
encoded_data = json_data.encode('utf-8')
compressed_data = gzip.compress(encoded_data)

return compressed_data

Lambda function URLs will treat this as a 200 OK response with the body being your binary data, but you won't have control over the headers, including CORS headers:

Response Status Code: 200
Response Headers:
  Date: Wed, 30 Apr 2025 18:50:49 GMT
  Content-Type: application/octet-stream
  Content-Length: 1464
  Connection: keep-alive
  x-amzn-RequestId: 96cd3d68-4e7f-4618-bfc4-b3afe5aeeab0
  X-Amzn-Trace-Id: Root=1-681270fc-3889864a2064506a1a764c5e;Parent=18d04ae2b3920edc;Sampled=0;Lineage=1:6ab91ab2:0

Response Body: gzip binary

If you need CORS, those headers can only be added by generating the JSON structured response. Lambda function URLs expect the body property to be a string when isBase64Encoded is false, so for binary data, you need to use base64 encoding.

AWS
answered 2 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions