Key Concept - ElysiaJS | ElysiaJS

ID: 2112https://elysiajs.com/key-concept.html
Source

Key Concept

MUST READ

Elysia has a number of important concepts that you need to understand to use it effectively.
This page covers most concepts that you should know before getting started.

Encapsulation

MUST READ

Elysia lifecycle methods are encapsulated to its own instance only.
Which means if you create a new instance, it will not share the lifecycle methods with others.

import { Elysia } from 'elysia';

const profile = new Elysia()
  .onBeforeHandle(({ cookie }) => {
    throwIfNotSignIn(cookie)
  })
  .get('/profile', () => 'Hi there!')

const app = new Elysia()
  .use(profile)
  // ⚠️ This will NOT have sign in check
  .patch('/rename', ({ body }) => updateProfile(body))

In this example, the isSignIn check will only apply to profile but not app.

Try changing the path in the URL bar to /rename and see the result

Elysia isolates lifecycle by default unless explicitly stated. This is similar to export in JavaScript, where you need to export the function to make it available outside the module.

To “export” the lifecycle to other instances, you must specify the scope.

import { Elysia } from 'elysia';

const profile = new Elysia()
  .onBeforeHandle(
    { as: 'global' },
    ({ cookie }) => {
      throwIfNotSignIn(cookie)
    }
  )
  .get('/profile', () => 'Hi there!')

const app = new Elysia()
  .use(profile)
  // This has sign in check
  .patch('/rename', ({ body }) => updateProfile(body))

Casting lifecycle to “global” will export lifecycle to every instance.
Learn more about this in scope.

Method Chaining

Important

Elysia code should ALWAYS use method chaining.
This is important to ensure type safety.

import { Elysia } from 'elysia';

new Elysia()
  .state('build', 1)
  // Store is strictly typed
  .get('/', ({ store: { build } }) => build)
  .listen(3000)

In the code above, state returns a new ElysiaInstance type, adding a typed build property.

Without method chaining

As Elysia type system is complex, every method in Elysia returns a new type reference.
Without using method chaining, Elysia doesn’t save these new types, leading to no type inference.

import { Elysia } from 'elysia';

const app = new Elysia()

app.state('build', 1)

app.get('/', ({ store: { build } }) => build)

// Property 'build' does not exist on type '{}'.

The error above indicates that type inference fails when not using method chaining.