4

I am working with an app built with KOA framework and I'm trying to figure out why a page is cached. In all browsers even a hard reload won't work. You literally have to clear cache to see the page update.

I want to add this to my index.js but I do not know where to add the line.

Can anyone help?

ctx.set('Cache-Control', 'no-cache');

I want to tell KOA to set the header of each page to not cache.

Kobi
  • 135,331
  • 41
  • 252
  • 292
Kenny Johnson
  • 452
  • 5
  • 15

1 Answers1

4

To apply the headers to all request, you need to write a middleware function (server-side):

// set header function
function setNoCacheHeaders(ctx) {
  ctx.set('Cache-Control', 'no-store, no-cache, must-revalidate')
  ctx.set('Pragma', 'no-cache')
  ctx.set('Expires', 0)
}

// Middleware that adds the header to all requests
app.use(async (ctx, next) => {
    await next()
    setNoCacheHeaders(ctx)
})

hope that helps ...

One more note: if you have problems with (browser-) cached javascript files, you can force it by requesting it with a version string or a random number as a query parameter. Something like this can force reloading your javascript (client side):

<script type="text/javascript">
    document.write('<scr'+'ipt src="/js/file.js?'+Math.random()+'" type="text/javascript"></scr'+'ipt>');
</script>
Sebastian Hildebrandt
  • 2,661
  • 1
  • 14
  • 20
  • Pragma is not really needed anymore for a while. Time to drop that header. Realistically `Cache-Control` are going to be supported by anyone. – Evert Jul 31 '18 at 14:31