How to implement caching on strapi API Layer?

Hello there!

I had the same problem, and I would like to share my solution with rest of people who can face this issue.

In our case we’re using Cloudflare as CDN. So we want to cache our API requests in Cloudflare, because we already have the CDN service and the cache service.

If you take a look to the cloudflare docs, they need you add a header: Cache-Control. So that’s what I did in Strapi API.

First of all, you need to have implemented a middleware solution on strapi. For more information, you can take a look to the official docs: Middlewares | Strapi Documentation.

Once you are able to create a new middleware, you may create a new one like this:

module.exports = () => {
  return async (ctx, next) => {
    await next();
    ctx.set('Cache-Control', 'public, max-age=3600');
  };
};

After that, you need to add this new middleware config and restart your strapi installation.

Once you have it all, then you only need to restart your strapi installation, and then every API request served by strapi will have a header Cache-Control, with 1 hour of TTL.

I hope this helps!
Jesús.