Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express.js compress middleware do not work

I have the following middlewares in my app:

app.use(express.favicon(__dirname + '/static/public/images/favicon.ico'));
app.use(express.compress());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser('SECRET!'));
app.use(express.static(__dirname + config.static_path, {maxAge: 365 * 86400000}));
app.use(express.session({secret: 'SECRET!'}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

headers example: jquery.js headers

But the static content do not compressing. What could be the problem?

like image 900
Kirill Avatar asked Dec 23 '13 11:12

Kirill


People also ask

What does compression middleware do?

js application, you can use the compression middleware in the main file of your Node. js app. This will enable GZIP, which supports different compression schemes. This will make your JSON response and other static file responses smaller.

Is Brotli better than GZIP?

The data is clear that Brotli offers a better compression ratio than GZIP. That is, it compresses your website “more” than GZIP. However, remember that it's not just about the compression ratio, it's also about how long it takes to compress and decompress data.

Does Express use GZIP?

Here compression means the gzip compression on the express server. You can use the compression middleware to add easy gzip compression to your server.

Is Express js outdated?

It is unmaintainedExpress has not been updated for years, and its next version has been in alpha for 6 years. People may think it is not updated because the API is stable and does not need change. The reality is: Express does not know how to handle async/await .


1 Answers

There are several reasons why your static content may not get compressed:

  • express.compress maintains a minimum file size threshold; files with a size below this threshold (default: 1024 bytes) won't get compressed;
  • express.compress also maintains a whitelist of content types to compress; if you're serving files with a content type that's not on that list, it won't get compressed either;

To fix:

app.use(express.compress({
  threshold : 0, // or whatever you want the lower threshold to be
  filter    : function(req, res) {
    var ct = res.get('content-type');
    // return `true` for content types that you want to compress,
    // `false` otherwise
    ...
  }
}));

(as a reference, this is the default filter function used)

like image 158
robertklep Avatar answered Oct 26 '22 13:10

robertklep