Caching in Netlify edge functions using Hono

Hi!

We’re currently building a new application that will serve as a proxy for our main NextJS application. This proxy will run at the edge and we’re using Hono as our framework of choice. So far, this going pretty well. Hono is running super fast and the DX is great!

However, I can’t seem to get the Netlify Edge cache to work. I’m adding the correct caching headers to the response, but I see that the cache isn’t being followed correctly. When I add a simple console.log in the route that I want to cache, I see the console.log every time I call that specific endpoint. When I inspect the headers, I see the correct headers being set, thus expecting that the cache is hit.

These are the headers that I set manually on the response:

response.headers.set("Netlify-CDN-Cache-Control", `public, max-age=1800, must-revalidate`);
response.headers.set("CDN-Cache-Control", `public, max-age=1800, must-revalidate`);
response.headers.set("Cache-Control", `public, max-age=1800, must-revalidate`);
response.headers.set("Netlify-Vary", "query=url");

Can you help with this issue? Perhaps I’m missing something or doing something incorrectly.

Looking forward to your reply!

With kind regards,

Peter

I’ve created a repository so that it’s easier to reproduce this issue:

When you create a new Netlify site using this source, you’ll see that /say-hi called is shown each time in the logs when you visit the /say-hi endpoint. Same happens for the /say-hello endpoint.

Alright, I was able to figure out the solution to my problem. It consisted of two steps:

  • I had to set the cache to "manual" for the Netlify edge function:
export const config: Config = {
	path: ["/*"],
	cache: "manual",
};
  • I had to strip the response headers from the previous response and add the cache headers. Somehow Netlify wasn’t able to cache the response with the original headers:
const headers = new Headers({
	"Content-Type": "application/json",
	"Netlify-CDN-Cache-Control": "public, max-age=1800, must-revalidate",
	"CDN-Cache-Control": "public, max-age=1800, must-revalidate",
	"Cache-Control": "public, max-age=1800, must-revalidate",
});

return new Response(response.body, { ...response, headers });

hi, thanks for writing back in and sharing your solution with the community. :+1:t6: