Skip to content

Life Cycle

It's recommended that you have read Essential life-cycle for better understanding of Elysia's Life Cycle.

Life Cycle allows us to intercept an important event at the predefined point allowing us to customize the behavior of our server as needed.

Elysia's Life Cycle event can be illustrated as the following. Elysia Life Cycle Graph

Below are the request life cycle available in Elysia:


Every life-cycle could be apply at both:

  1. Local Hook (route)
  2. Global Hook

Local Hook

The local hook is executed on a specific route.

To use a local hook, you can inline hook into a route handler:

typescript
import { 
Elysia
} from 'elysia'
import {
isHtml
} from '@elysiajs/html'
new
Elysia
()
.
get
('/', () => '<h1>Hello World</h1>', {
afterHandle
({
response
,
set
}) {
if (
isHtml
(
response
))
set
.
headers
['Content-Type'] = 'text/html; charset=utf8'
} }) .
get
('/hi', () => '<h1>Hello World</h1>')
.
listen
(3000)

Global Hook

Register hook into every handler that came after.

To add a global hook, you can use .on followed by a life cycle event in camelCase:

typescript
import { 
Elysia
} from 'elysia'
import {
isHtml
} from '@elysiajs/html'
new
Elysia
()
.
get
('/none', () => '<h1>Hello World</h1>')
.
onAfterHandle
(({
response
,
set
}) => {
if (
isHtml
(
response
))
set
.
headers
['Content-Type'] = 'text/html; charset=utf8'
}) .
get
('/', () => '<h1>Hello World</h1>')
.
get
('/hi', () => '<h1>Hello World</h1>')
.
listen
(3000)

Events from other plugins are also applied to the route so the order of code is important.