Skip to content

Instantly share code, notes, and snippets.

@JavascriptMick
Created September 11, 2024 16:52
Show Gist options
  • Save JavascriptMick/72fab79e399abaf48429a7a1e2d6f3b2 to your computer and use it in GitHub Desktop.
Save JavascriptMick/72fab79e399abaf48429a7a1e2d6f3b2 to your computer and use it in GitHub Desktop.
Accept gzipped json POST request in Nuxt3/H3
import { H3Event, readBody, eventHandler } from 'h3';
import { createGunzip } from 'zlib';
import { pipeline } from 'stream';
import { promisify } from 'util';
const pipelineAsync = promisify(pipeline);
export default eventHandler(async (event: H3Event) => {
let rawBody = '{}';
if (event.headers.get('content-encoding') === 'gzip') {
const { req } = event; // deprecated but it works... open to suggestion, readBody fails
const gunzip = createGunzip();
const decompressedData: Buffer = await new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
pipelineAsync(req, gunzip)
.then(() => {
gunzip.on('data', chunk => chunks.push(chunk));
gunzip.on('end', () => resolve(Buffer.concat(chunks)));
gunzip.on('error', reject);
})
.catch(reject);
});
rawBody = JSON.parse(decompressedData.toString());
} else {
rawBody = await readBody(event);
}
// .... Do something with rawBody
return 'ok';
});
@JavascriptMick
Copy link
Author

In case you want to send a gzipped post request from some client.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment