Skip to content

Best Practice? Changing URL of POST/PUT requests #986

Open
@twhid

Description

@twhid

Hi all,

I'm looking for some clarification (or suggested best practice) regarding changing the backend request URL for a POST/PUT (anything with a body). I have a use-case where I need to strip the leading segment from GraphQL requests when forwarding to our backend.

My understanding is that one needs to clone the request i.e. create a new request.

Fastly docs cover this use-case and suggest this code (ref):

addEventListener("fetch", event => {
  const req = event.request;
  const url = new URL(req.url);

  // Patttern match the URL with RegularExpression.
  let complexUrlRegex = new RegExp("^\/some-(custom|dynamic|complex)-pattern\/url\/path$", "g");
  let complexUrlMatch= complexUrlRegex.exec(url.pathname);
  
  // If the URL matches the pattern, rewrite URL path.
  if (complexUrlMatch) {
    url.pathname = "/status/200";
  } 
  let bereq = new Request(url, req);
  
  // Send request to origin and return response to client.
  return fetch(bereq, { backend: "origin_0" });
});

However, in my testing the post body doesn't appear to be copied into the new request. I've been using expressly and found that using request.clone() appears to work as intended but was hoping to get any feedback re: any downsides to using it. Example code:

// using expressly
const bereq = new Request('https://new.url/foo/', req.clone());

// also tested using the underlying Request (not ERequest from expressly)
// which results in an error in the viceroy runtime: 
// Warning: body ReadableStream closed during body streaming. Exception:
// (new Error("append_body: Invalid handle. Thrown when a request, response, dictionary, or body handle is not valid.\n", ""))
// Error: hyper::Error(User(Body), UnfinishedStreamingBody)
const bereq = new Request('https://new.url/foo/', req.event.request);
// req.event.request.clone() causes a panic 

Thanks for any insights.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions