In this tutorial, you will learn about caching and the content delivery API. Recently, I have been working on a ReactJS power single-page application that is powered by the Episerver content delivery API. As more content was added into the CMS the performance of the content API ground to a halt. Some requests would take over 10 seconds to return. If you looked at the API's response header you will notice the cache-control header is not set by default, as you can see:
One way to fix that is to set the cache headers in the response. To do this within C# you can create a custom attribute, similar to this:
Next, register the attribute within WebApiConfig
like this:
Just in case you did not know, you register the WebApiConfig within the 'global.ascx' like so:
Registering this code will add the cache headers to the output of the content delivery API, however, if you are using DXP and Cloudflare you may still have an issue. When using Cloudflare, you will notice this strange header called cf-cache-status: DYNAMIC
. If you look at the Cloudflare website, here, you can see that dynamic means the resource was not cached by default and your current caching configuration doesn't instruct Cloudflare to cache the resource. How come?
By default, Cloudflare/DXP is configured to only cache content that has a file extension. Assets like images that obviously have well-known file extensions (png, jpg, etc..) are cached. API responses are not. If you want Cloudflare to respect the content delivery API cache headers, you can try asking Episerver support to create a custom 'Page Rule' for you. The page rule can pattern match on URL. It is possible to create rules that specifically target the content delivery API. In recent years the DXP team are very reluctant to do this. If you get lucky, I suggest you add rules for:
If the page rule has been set up correctly you should see a HIT on the cf-cache-status, like so:
With the content delivery API output cached, the number of requests that get sent to the origin will be dramatically reduced, improving performance! You will need to figure out what cache durations you will need to add to the site. If you can not get caching from Cloudflare, then the other alternative is to cache the response locally within your application. This is not ideal and it takes extra effort. Putting a GraphQL layer in front of it will help, however, it will take a lot more development effort.