Zuplo logo

New Pre-Routing Hook

Changelog entry for New Pre-Routing Hook

New Pre-Routing Hook

The new Pre-Routing Hook allows you to manipulate an incoming request before it's checked for routing. For example, if you want all routes to be case insensitive you could just lowercase the URL as it comes into the gateway, as shown below:

runtime.addPreRoutingHook(async (request) => {
  const nr = new Request(request.url.toLowerCase(), request);
  return nr;
});

Another example would be URL path normalization to remove trailing slashes:

runtime.addPreRoutingHook(async (request) => {
  const url = new URL(request.url);
  if (url.pathname.length > 1 && url.pathname.endsWith("/")) {
    url.pathname = url.pathname.slice(0, -1);
    const nr = new Request(url, request);
    return nr;
  }
  return request;
});

Keep in mind that this will run on all requests so the code you use here needs to be appropriately performant and aware it can generate weird downstream effects by changing URLs and headers.

The method is async but reading and manipulating the request body is not recommended for performance reasons.