Cloudflare Worker Error: Steaming vs Buffer Response

Hi team

I’m playing around with Cloudflare workers and have hit the following error when trying to proxy a POST request (to a Wordpress blog):

TypeError: A request with a one-time-use body (it was initialized from a stream, not a buffer) encountered a redirect requiring the body to be retransmitted. To avoid this error in the future, construct this request from a buffer-like body initializer.

I tried the advice in this post (with reference to Requests, but I guessed it was the same) with no joy - even if I created a new response, the problem remained.

Can anybody advise on the best way to structure the response so that the redirect doesn’t cause an issue? Or is there a bigger problem with my code that I’m not seeing?

Full code below…



addEventListener('fetch', event => {

  var url = new URL(event.request.url);

  if (url.pathname.startsWith('/blog') || url.pathname === '/blog') {
    if (reqType === 'POST') {
      event.respondWith(handleBlogPost(event, url));
    } else {
      handleBlog(event, url);
  } else {

async function handleBlog(event, url) {
  var newBlog = "";
  var originUrl = url.toString().replace(
    '', newBlog);

async function handleBlogPost(event, url) {
  try {
    var newBlog = "";
    var srcUrl = "";

    const init = {
      method: 'POST',
      headers: event.request.headers,
      body: event.request.body
    var originUrl = url.toString().replace( srcUrl, newBlog );

    const response = await fetch(originUrl, init)

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

  } catch (err) {
    // Display the error stack.
    return new Response(err.stack || err)

For anybody else who comes across this problem, I got an amazing answer on SO:

Fixed by passing the whole request (event.request) in instead of the init block I’d constructed.


Thanks for sharing the solution

1 Like