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?
It is easy to serve static files using built-in middleware in Express. js called express. static.
Express serve-static middleware.
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.
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.
app.use(express.compress());
as the first middleware, remember the middleware live in a FIFO stack...static
part before the session parts, better yet, split them into separate routes (/app - with cookies, session and bodyParser, /static - with none)staticCache
it's deprecated and incompatible with static
, if you want a much more mature static serving component use st
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With