When considering performance optimization, browser caching is considered to be one of the best practices.

It's very easy to enable browser caching in express JS.

Ususally browser caching is preferable for static assets like css, js and image files.

For serving the static assets Express provides a built-in middleware function called static.

 express.static(path, [options]); 

path is used to specify the relative path for the assets location.

options is used to specify extra configurations. And this is the place we are going to specify the cahce information.

Setting browser cache for 2 hours.

 
app.use(express.static('public', {
    maxage : '2h'
    }
)) ;

This will set the assets caching time for 2 hours.
maxage is the default parameter used to set the header
cache-control : public, max-age=7200

Also it'll accept the value in milliseconds as well.

 
app.use(express.static('public', {
    maxage : 7200000
    }
)) ;

Verify the browser cache is properly set or not.

In order to veriy the browser cache set or not,

  • open the browser developer tools ( right click + inspect element).
  • Goto network tab and reload page
  • Use filter options to view assets in groups of JS or CSS or image files.
  • Click on the file name in network tab to inpect
  • Check for cache-control variable under response headers

The value should something like this.

 cache-control: public, max-age=31536000 

browser-cache_screen