ElysiaJS Development Skill
Always consult elysiajs.com/llms.txt for code examples and latest API.
Overview
ElysiaJS is a TypeScript framework for building Bun-first (but not limited to Bun) type-safe, high-performance backend servers. This skill provides comprehensive guidance for developing with Elysia, including routing, validation, authentication, plugins, integrations, and deployment.
When to Use This Skill
Trigger this skill when the user asks to:
- Create or modify ElysiaJS routes, handlers, or servers
- Setup validation with TypeBox or other schema libraries (Zod, Valibot)
- Implement authentication (JWT, session-based, macros, guards)
- Add plugins (CORS, OpenAPI, Static files, JWT)
- Integrate with external services (Drizzle ORM, Better Auth, Next.js, Eden Treaty)
- Setup WebSocket endpoints for real-time features
- Create unit tests for Elysia instances
- Deploy Elysia servers to production
Quick Start
Quick scaffold:
bash
1bun create elysia app
Basic Server
typescript
1import { Elysia, t, status } from 'elysia'
2
3const app = new Elysia()
4 .get('/', () => 'Hello World')
5 .post('/user', ({ body }) => body, {
6 body: t.Object({
7 name: t.String(),
8 age: t.Number()
9 })
10 })
11 .get('/id/:id', ({ params: { id } }) => {
12 if(id > 1_000_000) return status(404, 'Not Found')
13
14 return id
15 }, {
16 params: t.Object({
17 id: t.Number({
18 minimum: 1
19 })
20 }),
21 response: {
22 200: t.Number(),
23 404: t.Literal('Not Found')
24 }
25 })
26 .listen(3000)
Basic Usage
HTTP Methods
typescript
1import { Elysia } from 'elysia'
2
3new Elysia()
4 .get('/', 'GET')
5 .post('/', 'POST')
6 .put('/', 'PUT')
7 .patch('/', 'PATCH')
8 .delete('/', 'DELETE')
9 .options('/', 'OPTIONS')
10 .head('/', 'HEAD')
Path Parameters
typescript
1.get('/user/:id', ({ params: { id } }) => id)
2.get('/post/:id/:slug', ({ params }) => params)
Query Parameters
typescript
1.get('/search', ({ query }) => query.q)
2// GET /search?q=elysia → "elysia"
Request Body
typescript
1.post('/user', ({ body }) => body)
typescript
1.get('/', ({ headers }) => headers.authorization)
TypeBox Validation
Basic Types
typescript
1import { Elysia, t } from 'elysia'
2
3.post('/user', ({ body }) => body, {
4 body: t.Object({
5 name: t.String(),
6 age: t.Number(),
7 email: t.String({ format: 'email' }),
8 website: t.Optional(t.String({ format: 'uri' }))
9 })
10})
Nested Objects
typescript
1body: t.Object({
2 user: t.Object({
3 name: t.String(),
4 address: t.Object({
5 street: t.String(),
6 city: t.String()
7 })
8 })
9})
Arrays
typescript
1body: t.Object({
2 tags: t.Array(t.String()),
3 users: t.Array(t.Object({
4 id: t.String(),
5 name: t.String()
6 }))
7})
File Upload
typescript
1.post('/upload', ({ body }) => body.file, {
2 body: t.Object({
3 file: t.File({
4 type: 'image', // image/* mime types
5 maxSize: '5m' // 5 megabytes
6 }),
7 files: t.Files({ // Multiple files
8 type: ['image/png', 'image/jpeg']
9 })
10 })
11})
Response Validation
typescript
1.get('/user/:id', ({ params: { id } }) => ({
2 id,
3 name: 'John',
4 email: 'john@example.com'
5}), {
6 params: t.Object({
7 id: t.Number()
8 }),
9 response: {
10 200: t.Object({
11 id: t.Number(),
12 name: t.String(),
13 email: t.String()
14 }),
15 404: t.String()
16 }
17})
Standard Schema (Zod, Valibot, ArkType)
Zod
typescript
1import { z } from 'zod'
2
3.post('/user', ({ body }) => body, {
4 body: z.object({
5 name: z.string(),
6 age: z.number().min(0),
7 email: z.string().email()
8 })
9})
Error Handling
typescript
1.get('/user/:id', ({ params: { id }, status }) => {
2 const user = findUser(id)
3
4 if (!user) {
5 return status(404, 'User not found')
6 }
7
8 return user
9})
Guards (Apply to Multiple Routes)
typescript
1.guard({
2 params: t.Object({
3 id: t.Number()
4 })
5}, app => app
6 .get('/user/:id', ({ params: { id } }) => id)
7 .delete('/user/:id', ({ params: { id } }) => id)
8)
Macro
typescript
1.macro({
2 hi: (word: string) => ({
3 beforeHandle() { console.log(word) }
4 })
5})
6.get('/', () => 'hi', { hi: 'Elysia' })
Project Structure (Recommended)
Elysia takes an unopinionated approach but based on user request. But without any specific preference, we recommend a feature-based and domain driven folder structure where each feature has its own folder containing controllers, services, and models.
src/
├── index.ts # Main server entry
├── modules/
│ ├── auth/
│ │ ├── index.ts # Auth routes (Elysia instance)
│ │ ├── service.ts # Business logic
│ │ └── model.ts # TypeBox schemas/DTOs
│ └── user/
│ ├── index.ts
│ ├── service.ts
│ └── model.ts
└── plugins/
└── custom.ts
public/ # Static files (if using static plugin)
test/ # Unit tests
Each file has its own responsibility as follows:
- Controller (index.ts): Handle HTTP routing, request validation, and cookie.
- Service (service.ts): Handle business logic, decoupled from Elysia controller if possible.
- Model (model.ts): Define the data structure and validation for the request and response.
Best Practice
Elysia is unopinionated on design pattern, but if not provided, we can relies on MVC pattern pair with feature based folder structure.
- Controller:
- Prefers Elysia as a controller for HTTP dependant controller
- For non HTTP dependent, prefers service instead unless explicitly asked
- Use
onError to handle local custom errors
- Register Model to Elysia instance via
Elysia.models({ ...models }) and prefix model by namespace `Elysia.prefix('model', 'Namespace.')
- Prefers Reference Model by name provided by Elysia instead of using an actual
Model.name
- Service:
- Prefers class (or abstract class if possible)
- Prefers interface/type derive from
Model
- Return
status (import { status } from 'elysia') for error
- Prefers
return Error instead of throw Error
- Models:
- Always export validation model and type of validation model
- Custom Error should be in contains in Model
Elysia Key Concept
Elysia has a every important concepts/rules to understand before use.
Encapsulation - Isolates by Default
Lifecycles (hooks, middleware) don't leak between instances unless scoped.
Scope levels:
local (default) - current instance + descendants
scoped - parent + current + descendants
global - all instances
ts
1.onBeforeHandle(() => {}) // only local instance
2.onBeforeHandle({ as: 'global' }, () => {}) // exports to all
Method Chaining - Required for Types
Must chain. Each method returns new type reference.
❌ Don't:
ts
1const app = new Elysia()
2app.state('build', 1) // loses type
3app.get('/', ({ store }) => store.build) // build doesn't exists
✅ Do:
ts
1new Elysia()
2 .state('build', 1)
3 .get('/', ({ store }) => store.build)
Explicit Dependencies
Each instance independent. Declare what you use.
ts
1const auth = new Elysia()
2 .decorate('Auth', Auth)
3 .model(Auth.models)
4
5new Elysia()
6 .get('/', ({ Auth }) => Auth.getProfile()) // Auth doesn't exists
7
8new Elysia()
9 .use(auth) // must declare
10 .get('/', ({ Auth }) => Auth.getProfile())
Global scope when:
- No types added (cors, helmet)
- Global lifecycle (logging, tracing)
Explicit when:
- Adds types (state, models)
- Business logic (auth, db)
Deduplication
Plugins re-execute unless named:
ts
1new Elysia() // rerun on `.use`
2new Elysia({ name: 'ip' }) // runs once across all instances
Order Matters
Events apply to routes registered after them.
ts
1.onBeforeHandle(() => console.log('1'))
2.get('/', () => 'hi') // has hook
3.onBeforeHandle(() => console.log('2')) // doesn't affect '/'
Type Inference
Inline functions only for accurate types.
For controllers, destructure in inline wrapper:
ts
1.post('/', ({ body }) => Controller.greet(body), {
2 body: t.Object({ name: t.String() })
3})
Get type from schema:
ts
1type MyType = typeof MyType.static
Reference Model
Model can be reference by name, especially great for documenting an API
ts
1new Elysia()
2 .model({
3 book: t.Object({
4 name: t.String()
5 })
6 })
7 .post('/', ({ body }) => body.name, {
8 body: 'book'
9 })
Model can be renamed by using .prefix / .suffix
ts
1new Elysia()
2 .model({
3 book: t.Object({
4 name: t.String()
5 })
6 })
7 .prefix('model', 'Namespace')
8 .post('/', ({ body }) => body.name, {
9 body: 'Namespace.Book'
10 })
Once prefix, model name will be capitalized by default.
Technical Terms
The following are technical terms that is use for Elysia:
OpenAPI Type Gen - function name fromTypes from @elysiajs/openapi for generating OpenAPI from types, see plugins/openapi.md
Eden, Eden Treaty - e2e type safe RPC client for share type from backend to frontend
Resources
Use the following references as needed.
It's recommended to checkout route.md for as it contains the most important foundation building blocks with examples.
plugin.md and validation.md is important as well but can be check as needed.
references/
Detailed documentation split by topic:
bun-fullstack-dev-server.md - Bun Fullstack Dev Server with HMR. React without bundler.
cookie.md - Detailed documentation on cookie
deployment.md - Production deployment guide / Docker
eden.md - e2e type safe RPC client for share type from backend to frontend
guard.md - Setting validation/lifecycle all at once
macro.md - Compose multiple schema/lifecycle as a reusable Elysia via key-value (recommended for complex setup, eg. authentication, authorization, Role-based Access Check)
plugin.md - Decouple part of Elysia into a standalone component
route.md - Elysia foundation building block: Routing, Handler and Context
testing.md - Unit tests with examples
validation.md - Setup input/output validation and list of all custom validation rules
websocket.md - Real-time features
plugins/
Detailed documentation, usage and configuration reference for official Elysia plugin:
bearer.md - Add bearer capability to Elysia (@elysiajs/bearer)
cors.md - Out of box configuration for CORS (@elysiajs/cors)
cron.md - Run cron job with access to Elysia context (@elysiajs/cron)
graphql-apollo.md - Integration GraphQL Apollo (@elysiajs/graphql-apollo)
graphql-yoga.md - Integration with GraphQL Yoga (@elysiajs/graphql-yoga)
html.md - HTML and JSX plugin setup and usage (@elysiajs/html)
jwt.md - JWT / JWK plugin (@elysiajs/jwt)
openapi.md - OpenAPI documentation and OpenAPI Type Gen / OpenAPI from types (@elysiajs/openapi)
opentelemetry.md - OpenTelemetry, instrumentation, and record span utilities (@elysiajs/opentelemetry)
server-timing.md - Server Timing metric for debug (@elysiajs/server-timing)
static.md - Serve static files/folders for Elysia Server (@elysiajs/static)
integrations/
Guide to integrate Elysia with external library/runtime:
ai-sdk.md - Using Vercel AI SDK with Elysia
astro.md - Elysia in Astro API route
better-auth.md - Integrate Elysia with better-auth
cloudflare-worker.md - Elysia on Cloudflare Worker adapter
deno.md - Elysia on Deno
drizzle.md - Integrate Elysia with Drizzle ORM
expo.md - Elysia in Expo API route
nextjs.md - Elysia in Nextjs API route
nodejs.md - Run Elysia on Node.js
nuxt.md - Elysia on API route
prisma.md - Integrate Elysia with Prisma
react-email.d - Create and Send Email with React and Elysia
sveltekit.md - Run Elysia on Svelte Kit API route
tanstack-start.md - Run Elysia on Tanstack Start / React Query
vercel.md - Deploy Elysia to Vercel
examples/ (optional)
basic.ts - Basic Elysia example
body-parser.ts - Custom body parser example via .onParse
complex.ts - Comprehensive usage of Elysia server
cookie.ts - Setting cookie
error.ts - Error handling
file.ts - Returning local file from server
guard.ts - Setting mulitple validation schema and lifecycle
map-response.ts - Custom response mapper
redirect.ts - Redirect response
rename.ts - Rename context's property
schema.ts - Setup validation
state.ts - Setup global state
upload-file.ts - File upload with validation
websocket.ts - Web Socket for realtime communication
patterns/ (optional)
patterns/mvc.md - Detail guideline for using Elysia with MVC patterns