Netlify Functions Response Caching for Redirects

I am unable to cache redirect responses from Lambda functions. I have tried the following response, but the Cache-Status is always “Netlify Edge”; fwd=miss"

  return new Response(undefined, {
    status: 301,
    headers: {
      Location: "the url to redirect to",
      "Netlify-CDN-Cache-Control": "public, s-max-age=31536000, immutable",
      "Cache-Control": "public, max-age=31536000, immutable",
    },
  });

Example of a URL that should be cached in the CDN as long as possible

https://devshapes.com/zz/z9v7PJdmgJgXOBzTImVlz

Have you checked: Cannot get Netlify api endpoint caching to work as expected - Support - Netlify Support Forums

Yes, I have read that. Is there anything specific in that thread I should be aware of?

In my test URL, you can see all other network calls correctly cached, only the 301 is uncached. While it could be possible I am hitting a different CDN node every time, its unlikely to be the case when making the request from the same client repeatedly.

That’s not true. But if you can send a HAR file recording or the output of your curls, we can check.

It’s a public link, so you should be able to generate an HAR file from visiting the site at the posted link above. I have also attached an HAR as well.
devshapes.com.har (152.2 KB)

Can you try doing the same with Edge Functions and using their caching: Optional configuration for edge functions | Netlify Docs

I’ve been trying to use edge functions, but I get stuck on the experimental support for npm modules.

“There was an error when loading the “postgres” npm module. Support for npm modules in edge functions is an experimental feature. Refer to Support for npm modules in Edge Functions - Updates - Netlify Support Forums for more information.”

I have tried the workarounds in that thread such as Deno import maps, but I still get the same error during build.

Sorry, I totally missed thie before, but the problem might be happening because you’re using s-max-age instead of the s-maxage standard. Could you try to remove the extra -?

I’m using s-max-age now but I don’t see any difference in the caching.

I think it should be s-maxage and not s-max-age.

Sorry, mistyped that last reply. Here is the actual code.

  return new Response(undefined, {
    status: 301,
    headers: {
      Location: url || domain,
      "Netlify-CDN-Cache-Control": "public, s-maxage=31536000, immutable",
      "Cache-Control": "public, max-age=31536000, immutable",
    },
  });

Alright, I’ve asked the devs about it. Will let you know what they say.

This is a bug and would be fixed, but right now, you should be able to add another header like 'content-length': '0' and it would fix it.

That worked perfectly, thanks for the quick reply.

Glad to hear it! :+1:t6:

The original bug has been resolved and content-length is no longer needed.