Caching is frequently used for static resources and taken care of by a file-serving module or web server. However, there's nothing stopping us from implementing caching with dynamic resources as well.
The ETag is a cache mechanism for HTTP requests, which allows the client to make conditional requests.
Note
You can read more about the ETag mechanism and its usefulness at https://developer.yahoo.com/blogs/ydnfiveblog/high-performance-sites-rule-13-configure-etags-7211.html.
There are several NPM modules that handle ETag generation and conditional requests, but we can implement our own Express middleware to do this in a few lines of code. We need to set the ETag and check whether the current request matches that ETag. If it does, we will send 304 Not Modified
, and if it doesn't, we will send the whole body. The specification says that we shouldn't include content headers when sending 304 Not Modified
, so we will remove them if they exist. The full code for this middleware...