Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compression middleware order in express

Express API docs for app.use() say:

Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

Then, I see code like this all over the place:

import compression from 'compression';
import api from './api';
// some code 
app.use(compression() );
// some more code 
app.use(api);

Where api is the router which does res.send() calls.

As I see, compression middleware is registered before sending respose. Then how does it compress response? Is there some kind of hook to register callback after res.send() call?


1 Answers

The compression middleware is executed sequentially, but it's overloading the res.write res.on and res.end functions. So when the api will call those later, it wil run the compression code.

ref : https://github.com/expressjs/compression/blob/93586e75a0a1c5bbfd353c4cec1cfcee2e52adde/index.js#L78

like image 190
Gabriel Bleu Avatar answered May 23 '26 22:05

Gabriel Bleu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!