Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to leverage browser cache in node.js?

My website is running on node.js server and when i inspect my website on google page insight tool, it shows me to leverage browser cache. I have been searching a lot for this on internet but no luck yet. If anybody has any idea how leverage browser cache in node.js please let me know.

like image 226
Nishank Singla Avatar asked Jan 21 '15 18:01

Nishank Singla


People also ask

How do I leverage my browser cache?

To leverage your browser's caching generally means that you can specify how long web browsers should keep images, CSS and JS stored locally. That way the user's browser will download less data while navigating through your pages, which will improve the loading speed of your website.

How do I enable caching in NodeJS?

Implement caching with following approach: On API request, check if the cache has key already set using has(key) function. If the cache has the key, retrieve the cached value by get(key) function and use it instead of performing operation again. (This saves time)

How do you cache static resources using HTTP caching?

Here is what you need to remember while caching static resources on CDN or local cache server: Use Cache-control HTTP directive to control who can cache the response, under which conditions, and for how long. Configure your server or application to send validation token Etag. Do not cache HTML in the browser.


1 Answers

Browser cache is mostly controlled by the user, outside of Node's control. The only thing you can really do is to set max-age header on static files served by Node.js.

Assuming you're using express, to cache a file for one day:

app.use(express.static(__dirname + '/public', { maxAge: 86400000 }));
like image 70
Yuri Zarubin Avatar answered Oct 04 '22 06:10

Yuri Zarubin