Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set header cache control in KOA framework

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.

like image 940
Kenny Johnson Avatar asked Sep 15 '25 17:09

Kenny Johnson


1 Answers

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>
like image 153
Sebastian Hildebrandt Avatar answered Sep 17 '25 07:09

Sebastian Hildebrandt