Lifecycle Callbacks
onBefore, onAfter and onError run code around one handler without changing its result, for logging, metrics or tracing of a single route. They are options of the verbose form of defineCoreHandler() and defineErrorHandler().
The fragment below logs how long one route takes; buildReport() stands for the route's work:
typescript
app.get('/report', defineCoreHandler({
onBefore: (event) => {
event.store.start = performance.now();
},
onAfter: (event, response) => {
const ms = performance.now() - (event.store.start as number);
console.log(`${event.path} ${response?.status} ${ms.toFixed(1)}ms`);
},
fn: () => buildReport(),
}));Callbacks
| Option | Signature | Runs |
|---|---|---|
onBefore | (event) => unknown | before fn; a returned promise is awaited before fn is called |
onAfter | (event, response) => unknown | after the return value of fn became a Response; response is undefined when the handler produced none |
onError | (error, event) => unknown | when fn, onBefore or onAfter throws, including the 408 of a per-handler timeout |
- All three receive the event that
fnreceives, soevent.storecarries a value fromonBeforetoonAfter. - Their return values are ignored. To answer a request early, use middleware.
erroris anAppError(see Error Handling).
Order
A handler runs onBefore, then fn, then onAfter. Around event.next():
- The handlers after a middleware run inside its
fn. Their callbacks fire before the middleware'sonAfter, and thatonAfterreceives the downstream response. - For a middleware and a route that both set all callbacks, the order is: middleware
onBefore, middlewarefn, routeonBefore, routefn, routeonAfter, middlewareonAfter.
On failure:
- When
onBeforethrows,fndoes not run andonErrorfires. - When
onAfterthrows, the responsefnproduced is dropped andonErrorfires. onErrordoes not recover. Returning normally lets the error continue to the error handlers; throwing replaces it with the new error.onErrorfires for this handler's own failures. An error thrown by a handler that runs inside itsevent.next()does not fire it.- On an error handler, the callbacks fire only when that handler runs, which needs a pending error.
No App-Level Hooks
App has no hook registry and no on() method. Code that should wrap every handler, or every handler under a path, is a middleware: see Middleware Patterns.
The callback types are in the HandlerBaseOptions reference.