Best way to get origin response time in worker?


#1

I have this code(simplified) which seems to work, but some requests end up so fast that I am not sure if they actually that fast or the code is wrong:

requestStartTime = Date.now();
const response = await fetch(event.request);
requestEndTime = Date.now();
originTime = requestEndTime - requestStartTime;

is is possible for the requestEndTime line to run before response is fetched?


#2

The requestEndTime happens after the fetch is done, since you await it, but it doesn’t necessarily mean that the response body is loaded. You’d have to await the body too using eg const body = await response.text() if that’s something you care about.

Note that Cloudflare will cache requests for you if they have the proper headers. So the request might not actually go out to the origin server.

Also, using Date can be unreliable in fast requests, it isn’t necessarily correct. If you want to measure sub-millisecond you can use console.time, which logs to console.