Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
twhid opened this issue Sep 25, 2024 · 0 comments
Open

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

twhid opened this issue Sep 25, 2024 · 0 comments

Comments

@twhid
Copy link

twhid commented Sep 25, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant