Below is the code which most of the times developers just copy and paste.
var express = require('express')
var compression = require('compression')
var app = express()
app.use(compression())
Page on-the-fly compression (as pictured above) is the process of putting additional time into the page generation pipeline, so that the data can be transmitted faster. However, it has to transmit so much faster, that it makes up for the additional generation time:
dataGenerationTime + transmitionTime > dataGenerationTime + compressionTime + transmitionTime
When can compression go wrong? Most of the time, when the compression cannot compress the data a lot, hence the transmission time does not decrease enough to make up for the additional computation. That means, compressing content and sending it will take longer than just sending the uncompressed data.
Which data can trigger such a behavior? There are two types of data which are hard to compress and will lead to an increased delivery time:
What can be done in order to improve performance? Usually, all data should be optimized at build-time, not at run-time. For example Webpack can help you optimize your static website files and trigger image optimizations. CI can help you automate that step. Only data, which has to be generated by a server, should be compressed - and only if the file size is big enough. Profiling different sizes and types will give you more accurate information about when to use compression.
Mev-Rael
Executive Product Leader & Mentor for High-End Influencers and Brands @ mevrael.com
NEVER just "copy and paste".
As Marco said
Optimize at compile/build-time, not runtime
Compress your assets using a lot of already available node scripts and build tools.
On server side, enable http2 and nginx caching.
On application level - compress/compile views as well depending on language. If it is PHP and you use template engine, you might generate a final vanilla PHP file itself like Laravel is doing out of the box. Same with any template engine you use in Node. You might also remove all tabs/spaces from HTML to make it even smaller.
You HAVE to know how everything works on lower level and you won't have any questions ever again.
Start from "History of the Internet", "How the Internet works?", OSI model, HTTP1, http server (nginx) configuration, then you just apply that knowledge to your current needs. You don't need to do anything at the beginning, only ADAPT to a situation. Start small, simple.