Handler - ElysiaJS | ElysiaJS

ID: 2110https://elysiajs.com/essential/handler.html
Source

Handler

A handler is a function that accepts an HTTP request and returns a response.

import { Elysia } from 'elysia'

new Elysia()
  // the function `() => 'hello world'` is a handler
  .get('/', () => 'hello world')
  .listen(3000)

A handler may be a literal value and can be inlined.

import { Elysia, file } from 'elysia'

new Elysia()
  .get('/', 'Hello Elysia')
  .get('/video', file('kyuukurarin.mp4'))
  .listen(3000)

Using an inline value always returns the same value, which is useful for static resources like files.
Elysia can compile the response ahead of time to optimize performance.

TIP
Providing an inline value is not a cache.
Static resource values, headers and status can be mutated dynamically using the lifecycle.

Context

Context contains request information which is unique for each request and is not shared except for store (global mutable state).

import { Elysia } from 'elysia'

new Elysia()
  .get('/', (context) => context.path)
// ^ This is a context

Context can only be retrieved in a route handler. It consists of:

Property

  • body – HTTP message, form or file upload.
  • query – Query string, parsed as a JavaScript object (extracted from ?).
  • params – Elysia’s path parameters parsed as a JavaScript object.
  • headers – HTTP headers, e.g. User‑Agent, Content‑Type.
  • cookie – Global mutable signal store for interacting with cookies (get/set).
  • store – Global mutable store for the Elysia instance.

Utility Function

  • redirect – A function to redirect a response.
  • status – A function to return a custom status code.
  • set – Property to apply to the response:

Additional Property

  • request – Web Standard Request.
  • server – Bun server instance.
  • path – Pathname of the request.

Status

status is a function to return a custom status code with type narrowing.

import { Elysia } from 'elysia'

new Elysia()
  .get('/', ({ status }) => status(418, "Kirifuji Nagisa"))
  .listen(3000)

It is recommended to use the never‑throw approach to return status instead of throwing, because:

  • Allows TypeScript to check that a return value is correctly typed to the response schema.
  • Provides autocompletion for type narrowing based on status code.
  • Enables type narrowing for error handling using end‑to‑end type safety (Eden).

Set

set is a mutable property that forms a response accessible via Context.set.

import { Elysia } from 'elysia'

new Elysia()
  .get('/', ({ set, status }) => {
    set.headers = { 'X-Teapot': 'true' }

    return status(418, 'I am a teapot')
  })
  .listen(3000)

set.headers

Allows appending or deleting response headers represented as an object.

import { Elysia } from 'elysia'

new Elysia()
  .get('/', ({ set, status }) => {
    set.headers = { 'X-Teapot': 'true' }

    return status(418, 'I am a teapot')
  })
  .listen(3000)