worker is pretty much just doing a url rewrite and fetching
worker is pretty much just doing a url rewrite and fetching

fetch() in Date.now()s like so, then check the x-elapsed header: Date.now() only changes on I/O, so if theres something behind using heavy CPU doing a Date.now() -> fetch -> Date.now() would not only track the fetch time.
Date.now()Date.now()x-elapsedasync function handleRequest(request) {
// url rewriting
let url = request.url;
let host = request.headers.get("Host");
let path = new URL(request.url).pathname;
// redirect www.
if (url.startsWith("https://www.")) {
return Response.redirect(url.replace("https://www.", "https://"));
}
// if we are api
let isApiOrigin = (path.startsWith("/api/") || path == "/api");
if (isApiOrigin) {
url = url.replace(`https://${host}/api`, `https://api.${host}`);
} else {
// throw out query params for static pages
url = url.split("?")[0];
url = url.replace("https://","https://storage.googleapis.com/");
// if path does not contain an extension (eg /dashboard but not /script.js)
// or is explicitly a directory (eg /dashboard/) add the index.html
if (path.endsWith("/")) {
url = url.concat("index.html");
} else if (!path.split("/").pop().includes(".")) {
return Response.redirect(`https://${host}${path}/`, 308);
};
}
const response = await fetch(new Request(url,
{
body:request.body,
method:request.method,
headers:request.headers,
redirect:request.redirect,
}
));const start = Date.now();
let response = await fetch(new Request(url,
{
body:request.body,
method:request.method,
headers:request.headers,
redirect:request.redirect,
}
));
response = new Response(response.body, response);
response.headers.set("x-elapsed", Date.now() - start);