elysiajs by elysiajs/skills
npx skills add https://github.com/elysiajs/skills --skill elysiajs请始终查阅 elysiajs.com/llms.txt 以获取代码示例和最新的 API。
ElysiaJS 是一个用于构建 Bun 优先(但不限于 Bun)的类型安全、高性能后端服务器的 TypeScript 框架。本技能为使用 Elysia 进行开发提供了全面的指导,包括路由、验证、身份验证、插件、集成和部署。
当用户要求以下操作时触发此技能:
快速搭建脚手架:
bun create elysia app
import { Elysia, t, status } from 'elysia'
const app = new Elysia()
.get('/', () => 'Hello World')
.post('/user', ({ body }) => body, {
body: t.Object({
name: t.String(),
age: t.Number()
})
})
.get('/id/:id', ({ params: { id } }) => {
if(id > 1_000_000) return status(404, 'Not Found')
return id
}, {
params: t.Object({
id: t.Number({
minimum: 1
})
}),
response: {
200: t.Number(),
404: t.Literal('Not Found')
}
})
.listen(3000)
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
import { Elysia } from 'elysia'
new Elysia()
.get('/', 'GET')
.post('/', 'POST')
.put('/', 'PUT')
.patch('/', 'PATCH')
.delete('/', 'DELETE')
.options('/', 'OPTIONS')
.head('/', 'HEAD')
.get('/user/:id', ({ params: { id } }) => id)
.get('/post/:id/:slug', ({ params }) => params)
.get('/search', ({ query }) => query.q)
// GET /search?q=elysia → "elysia"
.post('/user', ({ body }) => body)
.get('/', ({ headers }) => headers.authorization)
import { Elysia, t } from 'elysia'
.post('/user', ({ body }) => body, {
body: t.Object({
name: t.String(),
age: t.Number(),
email: t.String({ format: 'email' }),
website: t.Optional(t.String({ format: 'uri' }))
})
})
body: t.Object({
user: t.Object({
name: t.String(),
address: t.Object({
street: t.String(),
city: t.String()
})
})
})
body: t.Object({
tags: t.Array(t.String()),
users: t.Array(t.Object({
id: t.String(),
name: t.String()
}))
})
.post('/upload', ({ body }) => body.file, {
body: t.Object({
file: t.File({
type: 'image', // image/* mime 类型
maxSize: '5m' // 5 兆字节
}),
files: t.Files({ // 多个文件
type: ['image/png', 'image/jpeg']
})
})
})
.get('/user/:id', ({ params: { id } }) => ({
id,
name: 'John',
email: 'john@example.com'
}), {
params: t.Object({
id: t.Number()
}),
response: {
200: t.Object({
id: t.Number(),
name: t.String(),
email: t.String()
}),
404: t.String()
}
})
import { z } from 'zod'
.post('/user', ({ body }) => body, {
body: z.object({
name: z.string(),
age: z.number().min(0),
email: z.string().email()
})
})
.get('/user/:id', ({ params: { id }, status }) => {
const user = findUser(id)
if (!user) {
return status(404, 'User not found')
}
return user
})
.guard({
params: t.Object({
id: t.Number()
})
}, app => app
.get('/user/:id', ({ params: { id } }) => id)
.delete('/user/:id', ({ params: { id } }) => id)
)
.macro({
hi: (word: string) => ({
beforeHandle() { console.log(word) }
})
})
.get('/', () => 'hi', { hi: 'Elysia' })
Elysia 采取非强制性的方法,但基于用户请求。如果没有特定的偏好,我们推荐基于功能和领域驱动的文件夹结构,其中每个功能都有自己的文件夹,包含控制器、服务和模型。
src/
├── index.ts # 主服务器入口
├── modules/
│ ├── auth/
│ │ ├── index.ts # 身份验证路由(Elysia 实例)
│ │ ├── service.ts # 业务逻辑
│ │ └── model.ts # TypeBox 模式/DTO
│ └── user/
│ ├── index.ts
│ ├── service.ts
│ └── model.ts
└── plugins/
└── custom.ts
public/ # 静态文件(如果使用静态插件)
test/ # 单元测试
每个文件都有其自己的职责,如下所示:
Elysia 在设计模式上没有强制要求,但如果没有提供,我们可以依赖 MVC 模式并结合基于功能的文件夹结构。
onError 处理本地自定义错误Elysia.models({ ...models }) 将模型注册到 Elysia 实例,并通过命名空间前缀 Elysia.prefix('model', 'Namespace.')Model.nameModel 派生的接口/类型status (import { status } from 'elysia')return Error 而不是 throw Error在使用 Elysia 之前,需要理解一些非常重要的概念/规则。
生命周期(钩子、中间件)不会泄漏到实例之间,除非有作用域。
作用域级别:
local(默认)- 当前实例 + 后代scoped - 父级 + 当前 + 后代global - 所有实例.onBeforeHandle(() => {}) // 仅限本地实例
.onBeforeHandle({ as: 'global' }, () => {}) // 导出到所有实例
必须链式调用。每个方法都返回新的类型引用。
❌ 不要这样做:
const app = new Elysia()
app.state('build', 1) // 丢失类型
app.get('/', ({ store }) => store.build) // build 不存在
✅ 这样做:
new Elysia()
.state('build', 1)
.get('/', ({ store }) => store.build)
每个实例都是独立的。声明你所使用的内容。
const auth = new Elysia()
.decorate('Auth', Auth)
.model(Auth.models)
new Elysia()
.get('/', ({ Auth }) => Auth.getProfile()) // Auth 不存在
new Elysia()
.use(auth) // 必须声明
.get('/', ({ Auth }) => Auth.getProfile())
全局作用域适用于:
显式声明适用于:
除非命名,否则插件会重新执行:
new Elysia() // 在 `.use` 时重新运行
new Elysia({ name: 'ip' }) // 在所有实例中只运行一次
事件应用于之后注册的路由。
.onBeforeHandle(() => console.log('1'))
.get('/', () => 'hi') // 有钩子
.onBeforeHandle(() => console.log('2')) // 不影响 '/'
仅限内联函数以获得准确的类型。
对于控制器,在内联包装器中解构:
.post('/', ({ body }) => Controller.greet(body), {
body: t.Object({ name: t.String() })
})
从模式中获取类型:
type MyType = typeof MyType.static
模型可以通过名称引用,特别适合记录 API
new Elysia()
.model({
book: t.Object({
name: t.String()
})
})
.post('/', ({ body }) => body.name, {
body: 'book'
})
模型可以通过 .prefix / .suffix 重命名
new Elysia()
.model({
book: t.Object({
name: t.String()
})
})
.prefix('model', 'Namespace')
.post('/', ({ body }) => body.name, {
body: 'Namespace.Book'
})
一旦使用 prefix,模型名称默认会首字母大写。
以下是 Elysia 使用的技术术语:
OpenAPI Type Gen - 来自 @elysiajs/openapi 的函数名 fromTypes,用于从类型生成 OpenAPI,请参阅 plugins/openapi.mdEden, Eden Treaty - 端到端类型安全的 RPC 客户端,用于在后端和前端之间共享类型根据需要参考以下资料。
建议查看 route.md,因为它包含了最重要的基础构建块和示例。
plugin.md 和 validation.md 也很重要,但可以根据需要查阅。
按主题划分的详细文档:
bun-fullstack-dev-server.md - 带有 HMR 的 Bun 全栈开发服务器。无需打包器的 React。cookie.md - 关于 cookie 的详细文档deployment.md - 生产部署指南 / Dockereden.md - 端到端类型安全的 RPC 客户端,用于在后端和前端之间共享类型guard.md - 一次性设置验证/生命周期macro.md - 将多个模式/生命周期组合为可重用的 Elysia 键值对(推荐用于复杂设置,例如身份验证、授权、基于角色的访问检查)plugin.md - 将 Elysia 的一部分解耦为独立组件route.md - Elysia 基础构建块:路由、处理器和上下文testing.md - 带有示例的单元测试validation.md - 设置输入/输出验证以及所有自定义验证规则的列表websocket.md - 实时功能官方 Elysia 插件的详细文档、使用和配置参考:
bearer.md - 为 Elysia 添加承载能力 (@elysiajs/bearer)cors.md - 开箱即用的 CORS 配置 (@elysiajs/cors)cron.md - 运行可以访问 Elysia 上下文的 cron 作业 (@elysiajs/cron)graphql-apollo.md - 集成 GraphQL Apollo (@elysiajs/graphql-apollo)graphql-yoga.md - 与 GraphQL Yoga 集成 (@elysiajs/graphql-yoga)html.md - HTML 和 JSX 插件设置和使用 (@elysiajs/html)jwt.md - JWT / JWK 插件 (@elysiajs/jwt)openapi.md - OpenAPI 文档和 OpenAPI Type Gen / 从类型生成 OpenAPI (@elysiajs/openapi)opentelemetry.md - OpenTelemetry、插装和记录跨度实用程序 (@elysiajs/opentelemetry)server-timing.md - 用于调试的服务器计时指标 (@elysiajs/server-timing)static.md - 为 Elysia 服务器提供静态文件/文件夹服务 (@elysiajs/static)将 Elysia 与外部库/运行时集成的指南:
ai-sdk.md - 在 Elysia 中使用 Vercel AI SDKastro.md - 在 Astro API 路由中使用 Elysiabetter-auth.md - 将 Elysia 与 better-auth 集成cloudflare-worker.md - 在 Cloudflare Worker 适配器上运行 Elysiadeno.md - 在 Deno 上运行 Elysiadrizzle.md - 将 Elysia 与 Drizzle ORM 集成expo.md - 在 Expo API 路由中使用 Elysianextjs.md - 在 Nextjs API 路由中使用 Elysianodejs.md - 在 Node.js 上运行 Elysianuxt.md - 在 API 路由上运行 Elysiaprisma.md - 将 Elysia 与 Prisma 集成react-email.d - 使用 React 和 Elysia 创建和发送电子邮件sveltekit.md - 在 Svelte Kit API 路由上运行 Elysiatanstack-start.md - 在 Tanstack Start / React Query 上运行 Elysiavercel.md - 将 Elysia 部署到 Vercelbasic.ts - 基础 Elysia 示例body-parser.ts - 通过 .onParse 自定义请求体解析器示例complex.ts - Elysia 服务器的综合用法cookie.ts - 设置 cookieerror.ts - 错误处理file.ts - 从服务器返回本地文件guard.ts - 设置多个验证模式和生命周期map-response.ts - 自定义响应映射器redirect.ts - 重定向响应rename.ts - 重命名上下文的属性schema.ts - 设置验证state.ts - 设置全局状态upload-file.ts - 带验证的文件上传websocket.ts - 用于实时通信的 Web Socketpatterns/mvc.md - 将 Elysia 与 MVC 模式一起使用的详细指南每周安装量
3.3K
代码仓库
GitHub 星标
58
首次出现
2026年1月19日
安全审计
安装于
opencode2.6K
github-copilot2.5K
codex2.4K
gemini-cli2.4K
cursor2.1K
amp2.1K
Always consult elysiajs.com/llms.txt for code examples and latest API.
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.
Trigger this skill when the user asks to:
Quick scaffold:
bun create elysia app
import { Elysia, t, status } from 'elysia'
const app = new Elysia()
.get('/', () => 'Hello World')
.post('/user', ({ body }) => body, {
body: t.Object({
name: t.String(),
age: t.Number()
})
})
.get('/id/:id', ({ params: { id } }) => {
if(id > 1_000_000) return status(404, 'Not Found')
return id
}, {
params: t.Object({
id: t.Number({
minimum: 1
})
}),
response: {
200: t.Number(),
404: t.Literal('Not Found')
}
})
.listen(3000)
import { Elysia } from 'elysia'
new Elysia()
.get('/', 'GET')
.post('/', 'POST')
.put('/', 'PUT')
.patch('/', 'PATCH')
.delete('/', 'DELETE')
.options('/', 'OPTIONS')
.head('/', 'HEAD')
.get('/user/:id', ({ params: { id } }) => id)
.get('/post/:id/:slug', ({ params }) => params)
.get('/search', ({ query }) => query.q)
// GET /search?q=elysia → "elysia"
.post('/user', ({ body }) => body)
.get('/', ({ headers }) => headers.authorization)
import { Elysia, t } from 'elysia'
.post('/user', ({ body }) => body, {
body: t.Object({
name: t.String(),
age: t.Number(),
email: t.String({ format: 'email' }),
website: t.Optional(t.String({ format: 'uri' }))
})
})
body: t.Object({
user: t.Object({
name: t.String(),
address: t.Object({
street: t.String(),
city: t.String()
})
})
})
body: t.Object({
tags: t.Array(t.String()),
users: t.Array(t.Object({
id: t.String(),
name: t.String()
}))
})
.post('/upload', ({ body }) => body.file, {
body: t.Object({
file: t.File({
type: 'image', // image/* mime types
maxSize: '5m' // 5 megabytes
}),
files: t.Files({ // Multiple files
type: ['image/png', 'image/jpeg']
})
})
})
.get('/user/:id', ({ params: { id } }) => ({
id,
name: 'John',
email: 'john@example.com'
}), {
params: t.Object({
id: t.Number()
}),
response: {
200: t.Object({
id: t.Number(),
name: t.String(),
email: t.String()
}),
404: t.String()
}
})
import { z } from 'zod'
.post('/user', ({ body }) => body, {
body: z.object({
name: z.string(),
age: z.number().min(0),
email: z.string().email()
})
})
.get('/user/:id', ({ params: { id }, status }) => {
const user = findUser(id)
if (!user) {
return status(404, 'User not found')
}
return user
})
.guard({
params: t.Object({
id: t.Number()
})
}, app => app
.get('/user/:id', ({ params: { id } }) => id)
.delete('/user/:id', ({ params: { id } }) => id)
)
.macro({
hi: (word: string) => ({
beforeHandle() { console.log(word) }
})
})
.get('/', () => 'hi', { hi: 'Elysia' })
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:
Elysia is unopinionated on design pattern, but if not provided, we can relies on MVC pattern pair with feature based folder structure.
onError to handle local custom errorsElysia.models({ ...models }) and prefix model by namespace `Elysia.prefix('model', 'Namespace.')Model.nameModelstatus (import { status } from 'elysia') for errorreturn Error instead of throw ErrorElysia has a every important concepts/rules to understand before use.
Lifecycles (hooks, middleware) don't leak between instances unless scoped.
Scope levels:
local (default) - current instance + descendants
scoped - parent + current + descendants
global - all instances
.onBeforeHandle(() => {}) // only local instance .onBeforeHandle({ as: 'global' }, () => {}) // exports to all
Must chain. Each method returns new type reference.
❌ Don't:
const app = new Elysia()
app.state('build', 1) // loses type
app.get('/', ({ store }) => store.build) // build doesn't exists
✅ Do:
new Elysia()
.state('build', 1)
.get('/', ({ store }) => store.build)
Each instance independent. Declare what you use.
const auth = new Elysia()
.decorate('Auth', Auth)
.model(Auth.models)
new Elysia()
.get('/', ({ Auth }) => Auth.getProfile()) // Auth doesn't exists
new Elysia()
.use(auth) // must declare
.get('/', ({ Auth }) => Auth.getProfile())
Global scope when:
Explicit when:
Plugins re-execute unless named:
new Elysia() // rerun on `.use`
new Elysia({ name: 'ip' }) // runs once across all instances
Events apply to routes registered after them.
.onBeforeHandle(() => console.log('1'))
.get('/', () => 'hi') // has hook
.onBeforeHandle(() => console.log('2')) // doesn't affect '/'
Inline functions only for accurate types.
For controllers, destructure in inline wrapper:
.post('/', ({ body }) => Controller.greet(body), {
body: t.Object({ name: t.String() })
})
Get type from schema:
type MyType = typeof MyType.static
Model can be reference by name, especially great for documenting an API
new Elysia()
.model({
book: t.Object({
name: t.String()
})
})
.post('/', ({ body }) => body.name, {
body: 'book'
})
Model can be renamed by using .prefix / .suffix
new Elysia()
.model({
book: t.Object({
name: t.String()
})
})
.prefix('model', 'Namespace')
.post('/', ({ body }) => body.name, {
body: 'Namespace.Book'
})
Once prefix, model name will be capitalized by default.
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.mdEden, Eden Treaty - e2e type safe RPC client for share type from backend to frontendUse 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.
Detailed documentation split by topic:
bun-fullstack-dev-server.md - Bun Fullstack Dev Server with HMR. React without bundler.cookie.md - Detailed documentation on cookiedeployment.md - Production deployment guide / Dockereden.md - e2e type safe RPC client for share type from backend to frontendguard.md - Setting validation/lifecycle all at oncemacro.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 componentroute.md - Elysia foundation building block: Routing, Handler and Contexttesting.md - Unit tests with examplesDetailed 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)Guide to integrate Elysia with external library/runtime:
ai-sdk.md - Using Vercel AI SDK with Elysiaastro.md - Elysia in Astro API routebetter-auth.md - Integrate Elysia with better-authcloudflare-worker.md - Elysia on Cloudflare Worker adapterdeno.md - Elysia on Denodrizzle.md - Integrate Elysia with Drizzle ORMexpo.md - Elysia in Expo API routenextjs.md - Elysia in Nextjs API routenodejs.md - Run Elysia on Node.jsnuxt.md - Elysia on API routebasic.ts - Basic Elysia examplebody-parser.ts - Custom body parser example via .onParsecomplex.ts - Comprehensive usage of Elysia servercookie.ts - Setting cookieerror.ts - Error handlingfile.ts - Returning local file from serverguard.ts - Setting mulitple validation schema and lifecyclemap-response.ts - Custom response mapperredirect.ts - Redirect responsepatterns/mvc.md - Detail guideline for using Elysia with MVC patternsWeekly Installs
3.3K
Repository
GitHub Stars
58
First Seen
Jan 19, 2026
Security Audits
Gen Agent Trust HubPassSocketWarnSnykWarn
Installed on
opencode2.6K
github-copilot2.5K
codex2.4K
gemini-cli2.4K
cursor2.1K
amp2.1K
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
validation.md - Setup input/output validation and list of all custom validation ruleswebsocket.md - Real-time featureshtml.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)prisma.md - Integrate Elysia with Prismareact-email.d - Create and Send Email with React and Elysiasveltekit.md - Run Elysia on Svelte Kit API routetanstack-start.md - Run Elysia on Tanstack Start / React Queryvercel.md - Deploy Elysia to Vercelrename.ts - Rename context's propertyschema.ts - Setup validationstate.ts - Setup global stateupload-file.ts - File upload with validationwebsocket.ts - Web Socket for realtime communication