Purge cache tags set in edge functions

I have a CMS where I store images. I want this images to be proxied and cached by Netlify and be able to purge the cache based on cache tags.

I have set the following:

  • a _redirects file which contains a rewrite: /files/* https://my_cms/files/:splat 200
  • an edge function that is acting like a middleware and adds the cache tags to the response:
export default async (req: Request, context: Context) => {
  const response = await context.next();
  // getCacheTagsForPath() is a custom function to build an array of cache tags.
  const cacheTags = getCacheTagsForPath(req.url);
  const headers = Object.fromEntries(response.headers.entries())
  return new Response(await response.blob(), {
    headers: {
      ...headers,
      'Cache-Tag': cacheTags.join(','),
      // Tell Netlify to cache the content up to 1 year.
      "Netlify-Cdn-Cache-Control": "public, s-maxage=31536000, must-revalidate",
      // Tell the browser to always revalidate.
      "Cache-Control": "public, max-age=0, must-revalidate"
    }
  });
};

export const config: Config = {
  path: "/files/*"
};

When I load an image using the Netlify domain, I can properly see the cache tag in the response (in the browser). The problem I have is with purging the cache by using the cache tag. I tried the http API and the js API from Caching | Netlify Docs and none worked, I still get the cached image. As soon as I purge the cache without specifying a tag (so for the entire site id), the change is immediately visible.

Is there something I do wrong? I have a feeling that somehow the cache tags set in the edge function response are actually not attached to the resource.

Not relevant to the question, but your Function can be simplified (and potentially more performant):

const cacheTags = getCacheTagsForPath(req.url)
const response = await context.next()
const headers = response.headers
headers.set('cache-tag', cacheTags.join(','))
headers.set('netlify-cdn-cache-control', 'public, s-maxage=31536000, must-revalidate')
headers.set('cache-control', 'public, max-age=0, must-revalidate')
return new Response(response, {
  headers
})

As for the original issue, could you let us know how can we reproduce this?

The cache clear by tag seems to work when I set the cache property to be “manual” in the exported config, so:

export const config: Config = {
  path: "/files/*",
  cache: "manual",
};

I have also set it like that in the netlify.toml file:

[[edge_functions]]
  cache = "manual"
  path = "/files/*"
  function = "proxy"

At least so far, this seems to work good, although it is not super intuitive. Found it out from: Optional configuration for edge functions | Netlify Docs