Plugin - ElysiaJS | ElysiaJS

ID: 2114https://elysiajs.com/essential/plugin.html
Source

Plugin

Plugin is a pattern that decouples functionality into smaller parts, enabling the creation of reusable components for your web server.

Interactive PlaygroundPlayground

Basic usage

To create a plugin you simply instantiate a new Elysia instance and expose the routes, decorators, or any other functionality you want to reuse:

import { Elysia } from 'elysia';

const plugin = new Elysia()
  .decorate('plugin', 'hi')
  .get('/plugin', ({ plugin }) => plugin);

const app = new Elysia()
  .use(plugin)
  .get('/', ({ plugin }) => plugin)
  .listen(3000);

You can use the plugin by passing the instance to Elysia.use.

The plugin will inherit all properties of the plugin instance such as state and decorate, but it will NOT inherit the plugin lifecycle by default (see Scope below).
Elysia also handles type inference automatically.


Scope

Elysia lifecycle methods are encapsulated to their own instance.
When you create a new instance it will not share 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));

Try changing the URL path to /rename and see the result.

Exporting the lifecycle to other instances requires specifying a scope.
By default the scope is local, meaning the lifecycle applies only to the current instance and its descendants.
To make it available globally, set as: 'global'.

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 it to every instance that applies the plugin (all parents, current, and descendants).

Scope level

Elysia offers three levels of scope:

  1. local (default) – applies to only the current instance and its descendants.
  2. scoped – applies to the parent, current instance, and descendants.
  3. global – applies to all instances that use the plugin (all parents, current, and descendants).

Let’s look at an example:

import { Elysia } from 'elysia';

const child = new Elysia()
  .get('/child', 'hi');

(Further examples demonstrating each scope level would follow here.)