Implementing caching in an API function Last updated: 07. Apr 2025
This function implements caching for an API endpoint by checking the 'If-Modified-Since' header and returning a 304 status if the content has not been modified.
Implementation steps:
- Server-Side (API): setHeader "Last-Modified" and check If-Modified-Since
- Client-Side: Make sure caching is enabled (if so, nothing needs to be changed)
- Testing: Make sure you haven't disabled caching in the developer toolbar
1. Server-Side: setHeader "Last-Modified" and check If-Modified-Since
// Format the site's last modified date
let formattedSiteModifiedDate = docly.format(request.sitemodified, "R");
docly.setHeader("Last-Modified", formattedSiteModifiedDate);
// Retrieve the 'If-Modified-Since' header from the request
let ifModifiedSinceHeader = docly.getHeader("If-Modified-Since");
if (ifModifiedSinceHeader) {
// Convert the 'If-Modified-Since' header to a Date object
let ifModifiedSinceDate = new Date(ifModifiedSinceHeader);
// Calculate the difference between the 'If-Modified-Since' date and the site's last modified date
let dateDifference = docly.dateDiff(ifModifiedSinceDate, request.sitemodified);
// If the difference in seconds is less than 1, set the result code to 304 (Not Modified)
if (dateDifference.TotalSeconds < 1) {
let formattedSiteModifiedDate = docly.format(request.sitemodified, "R");
docly.setHeader("Last-Modified", formattedSiteModifiedDate);
return docly.setResultCode(304);
}
}
// Return an embedded file?
// docly.downloadEmbeded(file, embeddedId, "filename.pdf");
// Return what ever object you want here (not cached)
return {
"ifModified": ifModifiedSinceHeader,
"siteModified": formattedSiteModifiedDate,
"diff": dateDifference.TotalSeconds
};
2. Client-Side: Make sure caching is enabled (if so, nothing needs to be changed)
Modern browsers generally cache responses based on HTTP headers (like `Last-Modified` or `ETag`). While the standard `fetch` API respects these headers, jQuery's AJAX functions (like `$.get` or `$.ajax`) might append a cache-busting parameter (`_={timestamp}`) by default for certain data types.
To ensure caching is allowed for a `$.get` request, explicitly set the `cache` option to `true`:
// Example: Using $.get with caching explicitly enabled
$.get("API/test", {
cache: true // Set cache to true to allow browser caching
}).then(function(data) {
// Handle the response data here
console.log("Data received:", data);
}).fail(function(jqXHR, textStatus, errorThrown) {
// Handle errors
console.error("Request Failed:", textStatus, errorThrown);
});