How can I gzip Netlify function reponse? It’s quite big 2MB JSON.
1 Like
Hi, you’ll need to gzip your response within your function directly. Something like:
const zlib = require('zlib');
const helloWorld = "<html><head><title>Gzipped hello world!</title></head><body><h1>Gzipped hello world!</h1></body></html>";
exports.handler = (event, context, callback) => {
zlib.gzip(helloWorld, (error, gzippedHelloWorld) => {
if(error) console.log(error);
const response = {
statusCode: 200,
body: gzippedHelloWorld.toString('base64'),
isBase64Encoded: true,
headers: {
'Content-Type': 'text/html',
'Content-Encoding': 'gzip'
}
};
callback(null, response);
});
};
Let me know if that works for you.
1 Like
I use this gzip.js
module to gzip JSON responses in my project:
const util = require('util')
const zlib = require('zlib')
const gzip = util.promisify(zlib.gzip)
async function gzipResponse(responseEncoded) {
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Content-Encoding': 'gzip'
},
body: (await gzip(responseEncoded)).toString('base64'),
isBase64Encoded: true,
}
}
module.exports = gzipResponse
And here is how to use gzip.js
in a Netlify function:
const gzipResponse = require('./gzip')
const { fixedReturn } = require('./returns/fixed_return')
exports.handler = async event => {
const input = JSON.parse(event.body)
const resultEncoded = JSON.stringify(fixedReturn(input))
return await gzipResponse(resultEncoded)
}
1 Like
That’s a good example! Thanks for sharing it.