Cache authenticated responses

I have written an API with that requires users to have a valid JWT in order to make requests.

Some endpoints return the same data to every user but they must be authenticated.

What i’d like to do is to cache these authenticated responses whilst ensuring that the endpoints cannot be accessed publicly. If two authenticated users called the same endpoint, then user 1 would get a response from the server and user 2 from Cloudflare cache.

Can this be done with Cloudflare? What the best way to implement this?

Probably using workers. Perhaps something like:

Thanks for sharing that code @cs-cf. I think in my particular case I’ll only need to verify the token and make sure that it is not expired so this could work.