Repository navigation
Description
Describe the feature
Hey all 👋🏻
right now, Nitro has very low-level support for adding Server-Timing headers. While it is possible to use, it feels like DX could be improved a lot here. Thus, I'd like to suggest this RFC!
Current state
As mentioned, the support for adding server timing already exists and is realized via globalThis. This works, but has some shortcomings:
export default defineEventHandler(async () => {
globalThis.__timing__.logStart('MY-LABEL')
someFunction() // Do something here
globalThis.__timing__.logEnd('MY-LABEL')
})- TypeScript support only work by defining types on your own via addition
.d.tsfile:
// env.d.ts
declare global {
var __timing__: {
logStart: (id: string) => void
logEnd: (id: string) => void
}
}
export { }-
No documentation. While the timing option is documented, there is no example or guide on how to actually use it.
-
When
timingis disabled, the above code will fail because no__timing__object will be injected via timing middleware. -
Lengthy code. Because the current API is rather low-level, the code is repetitive.
-
With the above code, server timings are not cleared and will persist through requests every now and then, mainly in dev.
Idea
Instead of using the low-level API directly, I propose to add a utility which will use the API under the hood but has improved DX, full TS support and will do nothing when timing is disabled. Ideally, it will even be treeshaken in this case (and replaced with a no-op function)
API
For the API, I was thinking about the following:
-
withServerTiming(fn, label)- A "wrapper" function, that will start server timing tracking before the function and will stop it after it was executed. -
startServerTiming(label)- Starts server timing with certain label -
stopServerTiming(label)- Stops server timing with certain label
Summary
This RFC proposes a Nitro utility to improve DX when adding Server-Timing headers. It will do nothing, when timing is disabled and will add info otherwise.
Additional information
- Would you be willing to help implement this feature?
Activity
danielroe commentedon Nov 14, 2022
I love it! Seems good to me. @pi0?
atinux commentedon Jan 27, 2023
Looks great to me!
TheAlexLichter commentedon Feb 10, 2023
Short bullet points from in-person discussion with @pi0:
event.$log(likeevent.$fetch) utilizing consolaor2e commentedon Aug 6, 2023
It would be great to control timings in prod-mode with an
envsuch asNITRO_TIMING