Search code examples
node.jskoakoa2

How do I uncompress compressed request data in Koa.js at server side?


I am developing an HTTP driven REST based application where the need of the project is such that I have to receive compressed gzipped JSON data at the server side. There are several modules available which demonstrate to compress response and sending them back but I didn't find anything which shows how to decompress request data received at the server.


Solution

  • It looks like this might work out of the box with koa-bodyparser. Under the hood koa-bodyparser uses co-body to parse the request body and co-body uses the inflate package to inflates the request body before parsing.

    The following code:

    const koa = require('koa');
    const app = new koa();
    const bodyParser = require('koa-bodyparser');
    
    app.use(bodyParser());
    
    app.use(function(ctx) {
      ctx.body = ctx.request.body.test;
    })
    
    app.listen(3000);
    

    and the following request

    curl \
      -H 'content-type: application/json' \
      -H 'Content-Encoding: gzip' \
      -XPOST \
      --data-binary @data.json.gz \
      localhost:3000
    

    with a data.json that was gzipped (raw looks like the below):

    {
      "test": "data"
    }
    

    Everything worked as expected.