Lifecycle
Lifecycle hooks are functions that are executed on a specific event during the request-response cycle.
They allow you to run custom logic at a certain point
This can be useful for tasks like logging, authentication, etc.
To register a lifecycle hook, you can pass it in the second argument of a route method, before the handler:
import { Elysia } from 'elysia'
.get('/1', () => 'Hello Elysia!')
beforeHandle({ request, status }) {
console.log('This is executed before handler')
console.log('This is executed after "beforeHandle"')
return 'Oh you are lucky!'
.get('/2', () => 'Hello Elysia!')
Here we use status(418) which is the “I’m a teapot” status code. You can also use the string name directly: status("I'm a teapot"). See Status for more on using status codes.
When beforeHandle returns a value, it will skip the handler and return the value instead.
This is useful for things like authentication, where you want to return a 401 Unauthorized response if the user is not authenticated.
See Life cycle, Before handle for a more detailed explanation.
Hook
A function that intercepts the lifecycle event. because a function “hooks” into the lifecycle event
Hook can be categorized into 2 types:
- Local hook - execute on a specific route
- Interceptor hook - execute on every route after the hook is registered
Local hook
A local hook is executed on a specific route.
To use a local hook, you can inline hook into a route handler:
// Similar to previous code snippet
import { Elysia } from 'elysia'
.get('/1', () => 'Hello Elysia!')
beforeHandle({ request, status }) {
console.log('Run before handler')
console.log('Run after "beforeHandle"')
return 'Oh you are lucky!'
.get('/2', () => 'Hello Elysia!')
Interceptor hook
Register hook into every handler that came after the hook is called for the current instance only.
To add an interceptor hook, call the lifecycle method, such as .onBeforeHandle():
import { Elysia } from 'elysia'
.get('/1', () => 'Hello Elysia!')
.onBeforeHandle(({ request, status }) => {
console.log('This is executed before handler')
// "beforeHandle" is applied
console.log('This is executed after "beforeHandle"')
return 'Oh you are lucky!'
// "beforeHandle" is also applied
.get('/2', () => 'Hello Elysia!')
Unlike Local Hook, Interceptor Hook will add the hook to every route that came after the hook is registered.
Assignment
Let’s put 2 types of hooks into practice.