Express static server cache control with max-age=0,must-revalidate

I have setup a simple static server using express.

var location = path.join(__dirname, 'public');
app.use(express.static(location, { cacheControl: true, setHeaders: function(res, path) { 
} }));

The request header is sent with If-None-Match and If-Modififed-Since and I can also see 304 Not Modified in the response in Chrome if I reload the page without modifying the files. And I get a 200 OK if I modify one of the files.

But why is my Chrome network tab showing the size of the file downloaded instead of saying (from memory cache) when the status code is 304 Not Modified ?

I was expecting the files to be loaded from cache if its not modified and served up from the server if modified.

Appreciate any help and guidance.

2 answers

  • answered 2017-06-17 18:30 sBanda

    When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server. This tag is then used to send a request with the If-Modified-Since or If-None-Match header witch in effect tells server to send 304 if the content still has that ETag.

    In your case Chrome is doing a request to ask the server should it use its cache there is an old post explaining this here.

    You might want to check out this website about increasing application performance via HTTP Cache Headers.

  • answered 2017-06-17 18:30 maninak

    @sBanda described the situation very well. Receiving a 304 is expected since the specified cache-control policy states the file as stale, yet the ETag check shows it hasn't change. You get the 304 because you could have not requested the specific resource, yet you did, wasting bandwidth and cpu load.

    What you should do to avoid it is something like this:

    const express       = require('express');
    const server        = express();
    const oneHour       = 3600000;    // 3600000msec == 1hour
    server.use(express.static('www', { maxAge: oneHour })); // Client-side file caching
    server.get('/', function(req, res) {
      res.sendFile(__dirname + '/index.html');