Extends context
Elysia provides a context with small utilities to help you get started.
You can extend Elysia’s context with:
-
Decorate
-
State
-
Derive
Decorate
Singleton, and immutable properties that are shared across all requests.
import { Elysia } from 'elysia'
.decorate('logger', new Logger())
.get('/', ({ logger }) => {
Decorated value it will be available in the context as a read-only property, see Decorate.
State
A mutable reference that is shared across all requests.
import { Elysia } from 'elysia'
.get('/', ({ store }) => {
State will be available in context.store that is shared across every request, see State.
The first two requests return 1, then 2. Increment store.count to update the shared state. Destructuring a number with ({ store: { count } }) copies its current value into a local variable. Incrementing that variable does not change store.count.
Derive
Decorate value is registered as a singleton.
Derive adds context values per request, after validation.
import { Elysia } from 'elysia'
.derive(({ headers: { authorization } }) => ({
.get('/', ({ authorization }) => authorization)
Any returned value will be available in context except status, which will be send to client directly, and abort the subsequent handlers.
derive runs before the handler, after input has been validated and converted. Return an object to add values to context, or return status() to end the request early.
Scope
State, and Decorate are shared across all requests, and instances.
Derive values are per request, and have an encapsulation scope (as they’re based on life-cycle event).
If you want to use a derived value from a plugin, you would have to declare a Scope.
import { Elysia } from 'elysia'
const plugin = new Elysia()
({ headers: { authorization } }) => ({
.get('/', ({ authorization }) => authorization)
Assignment
Let’s try to extend Elysia’s context.