In our daily browsing, you may sometimes encounter the issue where the content of websites does not refresh correctly or new changes are not displayed. The reason for such occurrences is usually due to the existence of caching mechanisms. Caching tends to load website content faster because the browser makes a repeated request for each file and caches them. In this case, in some situations, we may need to leverage cached responses.
Caching responses in HTTP essentially refers to the concept that the old content present in the cache is no longer valid and must be replaced with new content. Typically, this can be done using HTTP headers such as specific headers related to this task.
When caching, we typically think about how we can send the browser a message such as "this version you have, doesn't hurt anymore, please go and get the newer version!"
For example, one of the common ways to do this is by using special headers like Cache-Control. We can set this header to no-cache or no-store, forcing the browser to check the validity of current information.
Sample Code
Cache-Control: no-cache\r\nCache-Control: no-store\r\nETag: "abc123"\r\nIf-None-Match: "xyz789"\r\n
Line-by-Line Explanation of the Code
Cache-Control: no-cache
This line instructs the browser to consult the server before using the cached version to check if a newer version of the content exists.
Cache-Control: no-store
This instructs the browser not to store any information in the cache.
ETag: "abc123"
This is a unique identifier (Etiquette Tag) assigned to the sent content, which will be used to compare the current content with what is stored.
If-None-Match: "xyz789"
This directive tells the server to only respond if the content's identifier differs from the cached one.