Consider this Express.js server code snippet using compression middleware:
import express from 'express';
import compression from 'compression';
const app = express();
app.use(compression());
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000);What happens when a client sends a request with Accept-Encoding: gzip header?
import express from 'express'; import compression from 'compression'; const app = express(); app.use(compression()); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000);
Compression middleware automatically compresses responses when the client supports it.
The compression middleware checks the client's Accept-Encoding header and compresses the response accordingly. It also sets the Content-Encoding header to inform the client about the compression type.
You want to compress only JSON responses in your Express app. Which code snippet correctly achieves this?
Headers are case-insensitive and may include charset info.
The filter option receives req and res. The response header content-type may include charset, so checking with includes is safer. Header names are lowercase in Node.js.
Look at this Express app code:
import express from 'express';
import compression from 'compression';
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.use(compression());
app.listen(3000);Why are responses not compressed?
import express from 'express'; import compression from 'compression'; const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.use(compression()); app.listen(3000);
Middleware order matters in Express.
Middleware in Express runs in the order it is added. Adding compression after routes means it never runs before sending the response, so no compression happens.
Why do developers add compression middleware like compression in their Node.js servers?
Think about what compression means in everyday life.
Compression reduces the size of data sent over the network, making pages load faster and using less bandwidth.
Given this Express app snippet:
import express from 'express';
import compression from 'compression';
const app = express();
app.use(compression({ threshold: 1024 }));
app.get('/', (req, res) => {
res.send('Short');
});
app.listen(3000);If a client requests '/' with Accept-Encoding: gzip, what is the Content-Encoding header in the response?
import express from 'express'; import compression from 'compression'; const app = express(); app.use(compression({ threshold: 1024 })); app.get('/', (req, res) => { res.send('Short'); }); app.listen(3000);
Check the meaning of the threshold option in compression middleware.
The threshold option sets the minimum response size (in bytes) to compress. Since 'Short' is less than 1024 bytes, compression is skipped and no Content-Encoding header is set.