Changing Response before serving with Cloudflare Workers


#1

I am using fetch to request the original content and then I append in response.body and then return new Response(new-content)

But instead of showing content, it is showing [Object ReadableStream]

How to solve this?
I want to serve the modified content.


#2

If it’s a JSON response, you need to stringify JSON.stringify(response) before returning it to the browser.

If you’re streaming the response, see this:

Since you can’t do stringify when streaming.


#3

It’s not JSON response. It’s normal HTML content.


#4

Hi @w3dev,

Could you share the specific code you’re using to modify the response body? The [Object ReadableStream] string suggests that you are perhaps doing something like new Response(response.body + "new content"), thus stringifying response.body, which is a ReadableStream, not a string.

If you know for sure that the response is text (e.g., with if (response.headers.get("Content-Type").startsWith("text/")), you could use new Response(await response.text() + "new content").

Harris