h3 icon indicating copy to clipboard operation
h3 copied to clipboard

Better `Server-Timing` support

Open tolu opened this issue 2 months ago • 2 comments

This is really no biggie since multiple Server-Timing headers are perfectly allowed. But it could potentially save some bytes in the response.

Rationale

Adding server-timing headers is most commonly done at the code where you have some async code that you want to measure. The user/programmer could ofc use append instead of set already there, but it's easy to forget. Headers could also be added by some dependency, which might introduce multiple headers in the response.

As a very small improvement the mergeHeaders could ensure that all server-timing headers are combined into one.

Appending server-timing headers uses , to join multiple statements since ; is already used within a single value like this: db;desc="get users";dur=250;

The code in question

https://github.com/h3js/h3/blob/f4dfd793906fb335a7da8f3185127677a5ee2eb0/src/response.ts#L142-L155

I'd be happy to provide a PR if this is something that you might agree with 🙏

tolu avatar Oct 11 '25 12:10 tolu

Thanks for initiating the issue. It would definitely be an improvement for saving HTTP headers when using unmerged Server-Timing, however, I'm wondering if adding "runtime cost" is worth it (we have to add a check in merge that runs for every request on every H3 server, which might not even be hitting)

As an alternative, I was thinking we could introduce a server-timing H3 middleware that both makes DX more convenient to log server timings in event context and also adds a post hook middleware that collects + merges this header (so it is opt-in)

pi0 avatar Oct 11 '25 18:10 pi0

a server-timing middleware sounds like a much better plan, totally agree that the runtime cost probably isn't worth it 👍

I am a bit fond of the DX you get from Hono with https://hono.dev/docs/middleware/builtin/timing for instance.

I'd really like to give this a go if I can, but I'm entirely new to h3 - so if you could recommend a good place to look for learning about a good example of opt-in middleware (or util) in h3 I'd be stoked 🙏

What would you think of doing something like this:

  1. A general middleware for simplistic single value "total request time"
  2. And then perhaps a util along the lines of how the cookie-util works for adding more specialized timing like specific db-calls or outgoing requests?

Or can outgoing requests be automatically instrumented somehow?

tolu avatar Oct 11 '25 20:10 tolu