52

I have read that to avoid caching in Node.js, it is necessary to use:

res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');

But I don't know how to use it because I get errors when I put that line in my code.

My function (where I think I have to program the Cache-Control header) is:

function getFile(localPath, mimeType, res) {
  fs.readFile(localPath, function(err, contents) {
    if (!err) {
      res.writeHead(200, {
        "Content-Type": mimeType,
        "Content-Length": contents.length,
        "Accept-Ranges": "bytes",
      });
      // res.header('Cache-Control', 'no-cache');
      res.end(contents);
    } else {
      res.writeHead(500);
      res.end();
    }
  });
}

Does anyone know how to put no cache in my code?

thatguy
  • 21,059
  • 6
  • 30
  • 40
user2986808
  • 525
  • 1
  • 4
  • 6
  • 2
    Use [`res.header()`](http://expressjs.com/api.html#res.set) (and/or [`res.setHeader()`](http://nodejs.org/api/http.html#http_response_setheader_name_value)) before [`res.writeHead()`](http://nodejs.org/api/http.html#http_response_writehead_statuscode_reasonphrase_headers) if you want to mix them. `writeHead()` is final, so no additional headers can be added after it. – Jonathan Lonowski Dec 06 '13 at 17:14
  • hi thanks.. I have tried to put res.header() before but I got error. On the other hand res.setHeader seems to work – user2986808 Dec 09 '13 at 08:45

6 Answers6

149

Make use of a middleware to add no-cache headers. Use this middleware where-ever you intend to turn caching off.

function nocache(req, res, next) {
  res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
  res.header('Expires', '-1');
  res.header('Pragma', 'no-cache');
  next();
}

Use the middleware in your routes definition:

app.get('/getfile', nocache, sendContent);

function sendContent(req, res) {
  var localPath = 'some-file';
  var mimeType = '';
  fs.readFile(localPath, 'utf8', function (err, contents) {
    if (!err && contents) {
      res.header('Content-Type', mimeType);
      res.header('Content-Length', contents.length);
      res.end(contents);
    } else {
      res.writeHead(500);
      res.end();
    }
  });
}

Let me know if this works for you.

vmx
  • 7,989
  • 4
  • 22
  • 20
  • He's not using Express. – Brad Dec 07 '13 at 00:37
  • Hi vmx... thanks but Brad is right I am not using Express and I think your answer is useful using only Express... – user2986808 Dec 09 '13 at 08:32
  • 1
    Ok, even if you aren't using express, what essentially needed is to set the nocache headers. I'm adding the headers in a reusable middleware, otherwise you can set those headers in any way that works. – vmx Dec 09 '13 at 08:44
  • 6
    I don't think using or not using express matters, here. – vmx Dec 09 '13 at 08:45
54

Set these headers on your response:

'Cache-Control': 'private, no-cache, no-store, must-revalidate'
'Expires': '-1'
'Pragma': 'no-cache'

If you use express you can add this middleware to have no cache on all requests:

// var app = express()
app.use(function (req, res, next) {
    res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    res.header('Expires', '-1');
    res.header('Pragma', 'no-cache');
    next()
});
Pylinux
  • 11,278
  • 4
  • 60
  • 67
32

You've already written your headers. I don't think you can add more after you've done that, so just put your headers in your first object.

res.writeHead(200, {
  'Content-Type': mimeType,
  'Content-Length': contents.length,
  'Accept-Ranges': 'bytes',
  'Cache-Control': 'no-cache'
});
Brad
  • 159,648
  • 54
  • 349
  • 530
9

You can use nocache Middleware to turn off caching.

npm install --save nocache

Apply the middleware to your app

const nocache = require('nocache');
...
app.use(nocache());

This disables browser caching.

Lanil Marasinghe
  • 2,785
  • 24
  • 24
2

Pylinux's answer worked for me, but upon further inspection, I found the helmet module for express that handles some other security features for you.

http://webapplog.com/express-js-security-tips/

To use, install and require helmet in express.js, then call app.use(helmet.noCache());

bmw15
  • 223
  • 3
  • 8
0

After spelunking through source code for the express and fresh modules, this works from the server side (before res.end is called):

req.headers['if-modified-since'] = undefined;
req.headers['if-none-match'] = undefined;

Nasty, but it works.

Dale Anderson
  • 1,681
  • 16
  • 15