How to cache REST request of your web application by using CloudFlare? In this article you can find example of Cloudflare settings to cache API requests.
If you are having your SPA app which is communicating with your backend by using REST API requests, there is a good chance that you want to cache some of these requests and serve them faster to your users.
In our example we will cache all public posts lists, and single post requests. In our application, all api calls to get post (or multiple of them) are going to api/post/... rest point.
So what we need to do is to cache all request going to that point.
Here are the steps needed
- Open cloudlflare and go to Page rules section
- Click on "Create page rule"
- Type in your domain and api/post path: https://yourdomain.com/api/post/*
- Create these rules: Cache Level: Cache Everything, Edge Cache TTL: 2 hours, Cache Deception Armor: On, Origin Cache Control: On
And now when you send you API request api/post/single-post which should be cached, in response headers you should see cf-cache-status: MISS which means, this is first request and cloudflare missed to return cached version, but current request is cached.
So, if you call same API request again, this time response header will contain cf-cache-status: HIT which means your request is cached, and cloudflare just returned cached version of it - without contacting your server.