---
title: "Encapsulation"
description: "Elysia hooks are encapsulated to its own instance only. If you create a new instance, it will not share hooks with other instances."
url: "https://next.elysiajs.com/tutorial/getting-started/encapsulation/"
---

# Encapsulation

Elysia hooks are **encapsulated** to its own instance only.

If you create a new instance, it will not share hooks with other instances.

```ts
import { Elysia } from 'elysia'

const profile = new Elysia()
  .onBeforeHandle(
    ({ query: { name }, status }) => {
      if(!name)
        return status(401)
    }
  )
  .get('/profile', () => 'Hi!')

new Elysia()
  .use(profile)
  .patch('/rename', () => 'Ok! XD')
  .listen(3000)
```

<!--astro:end-->

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



**Elysia isolates lifecycle** 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.

### Scope

There are 3 scopes available:

1. **local** (default) - apply to only current instance and descendant only
2. **plugin** - apply to parent, current instance and descendants
3. **global** - apply to all instance that apply the plugin (all parents, current, and descendants)

In our case, we want to apply the sign-in check to the `app` which is a direct parent, so we can use either **plugin** or **global**.

```ts
import { Elysia } from 'elysia'

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

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

<!--astro:end-->

Casting lifecycle to **“plugin”** will export lifecycle to **parent instance**. While **“global”** will export lifecycle to **all instances** that has a plugin.

Learn more about this in [scope](/essential/plugin/#scope-level).

## Guard

Similar to lifecycle, **schema** is also encapsulated to its own instance.

We can specify guard scope similar to lifecycle.

```typescript
import { Elysia, t } from 'elysia'

const user = new Elysia()
  .guard('plugin', {
    query: t.Object({
      age: t.Number(),
      name: t.Optional(t.String())
    }),
    beforeHandle({ query: { age }, status }) {
      if(age < 18) return status(403)
    }
  })
  .get('/profile', () => 'Hi!')
  .get('/settings', () => 'Settings')
```

It’s very important to note that every hook will affect all routes **after** its declaration.

See [Scope](/essential/plugin/#scope) for more information.

## Assignment

Let’s define a scope for `nameCheck`, and `ageCheck` to make our app works.
