Hello Cloudflare Community,
I am experiencing an issue with caching POST requests using a worker. Below is the worker code I have in place:
export default {
async fetch(request, env, ctx) {
// Function to hash the request body using SHA-256
async function sha256(message) {
// Encode as UTF-8
const msgBuffer = new TextEncoder().encode(message);
// Hash the message
const hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer);
// Convert bytes to hex string
return [...new Uint8Array(hashBuffer)]
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
try {
if (request.method.toUpperCase() === "POST") {
// Clone and read the request body
const body = await request.clone().text();
// Hash the request body to use it as a part of the cache key
const hash = await sha256(body);
const cacheUrl = new URL(request.url);
// Store the URL in cache by appending the body's hash
cacheUrl.pathname = "/posts" + cacheUrl.pathname + hash;
// Convert to a GET to be able to cache
const cacheKey = new Request(cacheUrl.toString(), {
headers: request.headers,
method: "GET",
});
const cache = caches.default;
// Find the cache key in the cache
let response = await cache.match(cacheKey);
// Otherwise, fetch response to POST request from origin
if (!response) {
response = await fetch(request);
// Clone the response to modify headers and store in cache
let newResponse = new Response(response.body, response);
// Ensure Cache-Control is set correctly
newResponse.headers.set('Cache-Control', 'public, max-age=3600'); // Cache for 1 hour
ctx.waitUntil(cache.put(cacheKey, newResponse.clone()));
return newResponse;
}
// Revalidate the cache to ensure the headers are correct
response = new Response(response.body, response);
response.headers.set('Cache-Control', 'public, max-age=3600'); // Cache for 1 hour
return response;
}
return fetch(request);
} catch (e) {
return new Response("Error thrown " + e.message, { status: 500 });
}
},
};
I have noticed in the Cache Performance section that my endpoint is being served from the cache sometimes. However, when I check the Workers Analytics dashboard, it shows that no subrequests were cached. Here are some screenshots to illustrate the issue (Cache performance at the top and worker analytics at the bottom, filtered on the specific route) :
P.S: It is my first message on the forum, apologies if the format is wrong.
Could someone please help me understand why the Workers Analytics dashboard is not showing cached subrequests despite the Cache Performance section indicating that the requests are being served from the cache?
Any assistance or pointers would be greatly appreciated!