---
title: "Guard"
description: "Elysia provides a guard method to bulk add hooks and schema to multiple routes at once."
url: "https://next.elysiajs.com/tutorial/getting-started/guard/"
---

# Guard

When you need to apply multiple hooks to your application, instead of repeating hooks multiple times, you can use `guard` to bulk add hooks to your application.

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

new Elysia()
  .onBeforeHandle(({ query: { name }, status }) => {
    if(!name) return status(401)
  })
  .onBeforeHandle(({ query: { name } }) => {
    console.log(name)
  })
  .onAfterResponse(({ responseValue }) => {
    console.log(responseValue)
  })
  .guard({
    beforeHandle: [
      ({ query: { name }, status }) => {
        if(!name) return status(401)
      },
      ({ query: { name } }) => {
        console.log(name)
      }
    ],
    afterResponse({ responseValue }) {
      console.log(responseValue)
    }
  })
  .get(
    '/auth',
    {
      query: t.Object({
        name: t.String()
      })
    }, ({ query: { name = 'anon' } }) => `Hello ${name}!`
  )
  .get(
    '/profile',
    {
      query: t.Object({
        name: t.String()
      })
    }, ({ query: { name = 'anon' } }) => `Hello ${name}!`
  )
  .listen(3000)
```

Not only that, you can also apply **schema** to multiple routes using `guard`.

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

new Elysia()
  .guard({
    beforeHandle: [
      ({ query: { name }, status }) => {
        if(!name) return status(401)
      },
      ({ query: { name } }) => {
        console.log(name)
      }
    ],
    afterResponse({ responseValue }) {
      console.log(responseValue)
    },
    query: t.Object({
      name: t.String()
    })
  })
  .get(
    '/auth',
    {
      query: t.Object({
        name: t.String()
      })
    }, ({ query: { name = 'anon' } }) => `Hello ${name}!`
  )
  .get(
    '/profile',
    {
      query: t.Object({
        name: t.String()
      })
    }, ({ query: { name = 'anon' } }) => `Hello ${name}!`
  )
  .listen(3000)
```

This will apply hooks and schema to every route **after .guard** is called in the same instance.

See [Guard](/essential/plugin/#guard) for more information.

## Assignment

Let’s put 2 types of hooks into practice.
