Edge Functions

Handling Compressed Requests

Handling Gzip compressed requests.


To decompress Gzip bodies, you can use gunzipSync from the node:zlib API to decompress and then read the body.


_33
import { gunzipSync } from 'node:zlib'
_33
_33
Deno.serve(async (req) => {
_33
try {
_33
// Check if the request body is gzip compressed
_33
const contentEncoding = req.headers.get('content-encoding')
_33
if (contentEncoding !== 'gzip') {
_33
return new Response('Request body is not gzip compressed', {
_33
status: 400,
_33
})
_33
}
_33
_33
// Read the compressed body
_33
const compressedBody = await req.arrayBuffer()
_33
_33
// Decompress the body
_33
const decompressedBody = gunzipSync(new Uint8Array(compressedBody))
_33
_33
// Convert the decompressed body to a string
_33
const decompressedString = new TextDecoder().decode(decompressedBody)
_33
const data = JSON.parse(decompressedString)
_33
_33
// Process the decompressed body as needed
_33
console.log(`Received: ${JSON.stringify(data)}`)
_33
_33
return new Response('ok', {
_33
headers: { 'Content-Type': 'text/plain' },
_33
})
_33
} catch (error) {
_33
console.error('Error:', error)
_33
return new Response('Error processing request', { status: 500 })
_33
}
_33
})