Hey there! Simon from the Edge Functions team here. Welcome back to the forums
I checked your code, and have a hypothesis of what’s happening:
By default, the Netlify CDN redirects requests from /foo to /foo/ (see docs). That means that for requests to /cache-keys, context.next() will return a Response with an empty body and a 301 status. Your code doesn’t take that into account. It takes that empty body and uses it in the 200 response. I’d expect that to result in an empty body, but apparently it results in garbled text, for whatever reason. I’ll make a note internally to investigate that, but I think this unrelated to your issue.
To check this hypothesis, could you try changing your edge function so that it only modifies 200 requests? A little like this:
Also, bonus tip - always try to prevent calling response.text if you can. That will buffer the response in memory and decrease your time to first byte significantly. You’re probably already aware of this and just used it for debugging purposes - still wanted to point it out
Thanks for getting back. Your suggestion works.
Did you mean “prevent logging response.text”? Because I intend to modify the response, so there is no way getting around calling await response.text()?
Compared to response.text(), which buffers the full response body before you can process it, this TransformStream approach allows you to transform the body as it arrives.
This is not an optimisation you absolutely need, but if your site has performance constraints (think marketing pages or e-commerce) then you should always try to prevent buffering.
Hi, just an update: Does the streaming transform work for you? I got an error “Readable stream is unlocked”. May be I don’t need to read stream, but I’d like to explore if it is possible.
That sounds like you’re trying to read the stream and then transform it. That won’t work, you can only have a single reader - take a look at ReadableStream: tee() method - Web APIs | MDN if you absolutely need to read it twice.