Monthly Archives: February 2020

Express server and compression

You may want to turn on compression within your express service(s) in which case simply run

yarn add compression

and we just need to add to our server code like this

import express from "express";
import compression from "compression";
 
const app = express();
const server = http.createServer(app);
 
app.use(compression());
 
const port = 4000;
server.listen(port, 
  () => console.log(`Server on port ${port}`)
);

Now, in many case you’ll possibly already have the client header including the following

Accept-Encoding: gzip, compress, br

or you can set the headers yourself and express will serve up gzip compressed responses.

Remember though, that compression happens based upon reading an amount of data before starting to stream/send the response, so small(ish) amounts of data will not benefit from any performance increases, whereas large amounts of data will by the very nature of compression, reduce the amount of data being transferred and therefore you should see a performance increase.

See also Compression in HTTP.