Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static(), staticCache(), and compress() node.js connect middleware

I have an Express 3.0 app and I'm trying to use the static(), staticCache(), and compress() middleware to serve and compress my static files. This is my current app.configure() function:

 app.configure(function() {
  app.use(express.favicon(__dirname + '/public/favicon.ico', {maxAge: 86400000}));
  app.use(express.bodyParser());
  app.use(express.cookieParser('foo'));
  app.set('views', __dirname + '/views');
  app.engine('.html', mustache({cache: true}).render);
  app.use(express.session({ store: sessionStore, secret: 'foo'}));
  app.use(express.staticCache());
  app.use(express.static(__dirname + '/public', {maxAge: 86400000}));
  app.use(express.compress());
});

// routes are loaded here

With this configuration, YSlow reports that my .css and .js files are not compressed and I can't get a cache hit without clearing my browser and refreshing the page multiple times. I also tried putting in a debug statement in the staticCache middleware to report cache hits and running ab -n 10000 -c 500 shows 0 cache hits.

Obviously I'm doing something wrong (I'm guessing the order or options are messed up) but I can't figure out what it is. Anybody have a working example with these three pieces of middleware working correctly together?

like image 340
Bill Avatar asked Apr 18 '12 21:04

Bill


People also ask

Which middleware is used to serve static resources in Node JS?

It is easy to serve static files using built-in middleware in Express. js called express. static.

What is the middleware that needs to be added to serve static resources?

Express serve-static middleware.

What does Express static () return?

use() function executes middleware in order. The express. static() middleware returns an HTTP 404 if it can't find a file, so that means you should typically call app.

What is static middleware in Express?

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The function signature is: express. static(root, [options]) The root argument specifies the root directory from which to serve static assets.


1 Answers

  • start by putting the app.use(express.compress()); as the first middleware, remember the middleware live in a FIFO stack...
  • put the static part before the session parts, better yet, split them into separate routes (/app - with cookies, session and bodyParser, /static - with none)
  • ohh, and forget about staticCache it's deprecated and incompatible with static, if you want a much more mature static serving component use st
like image 128
Refael Ackermann Avatar answered Sep 27 '22 20:09

Refael Ackermann