elysia

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Elysia Developer Guide

Elysia 开发者指南

This skill provides guidelines, patterns, and best practices for working with the Elysia framework in this project.
本技能提供了在本项目中使用Elysia框架的开发规范、模式和最佳实践。

Quick Start

快速入门

For detailed development guidelines, imports, and patterns, please refer to
references/patterns.md
in this skill directory.
如需了解详细的开发规范、导入规则和模式,请参考本技能目录下的
references/patterns.md

Core Philosophy

核心理念

  • Pattern-agnostic but feature-based structure recommended
  • "1 Elysia instance = 1 controller" principle
  • Strong typing with TypeBox for runtime validation
  • Centralized error handling and consistent responses
  • Production-ready deployment strategies
  • 推荐采用不限制模式但基于功能的结构
  • 遵循**「1 Elysia实例 = 1个控制器」**原则
  • 搭配TypeBox实现强类型运行时校验
  • 集中式错误处理和统一的响应格式
  • 生产可用的部署策略

Structure, Routing & Controllers

结构、路由与控制器

Essential Organization Patterns

核心组织模式

  • App as controller: Treat each
    new Elysia({ prefix })
    instance as the controller for that feature. Do not pass entire class methods directly as handlers. Instead, inline a small handler that calls service functions.
  • Feature folders: Use a feature-based structure:
    • src/modules/<feature>/index.ts
      - Elysia controller (routes, guards, cookies)
    • src/modules/<feature>/service.ts
      - business logic (no HTTP context)
    • src/modules/<feature>/model.ts
      - schemas & types via
      t
      (TypeBox)
    • Keep shared utilities in
      src/utils/*
      .
  • Method chaining: Prefer fluent chaining on the Elysia instance for routes, guards, plugins.
  • Plugins: Encapsulate cross-cutting concerns in plugins via
    .use()
    (e.g., OpenAPI, JWT, CORS).
  • Context hygiene: If a service needs request data, keep it in the controller and pass only the relevant fields into the service function.
  • 应用即控制器:将每个
    new Elysia({ prefix })
    实例视为对应功能的控制器。不要直接将整个类方法作为处理程序传入,而是内联一个调用服务函数的小型处理程序。
  • 功能文件夹:采用基于功能的结构:
    • src/modules/<feature>/index.ts
      - Elysia控制器(路由、守卫、Cookie处理)
    • src/modules/<feature>/service.ts
      - 业务逻辑(无HTTP上下文)
    • src/modules/<feature>/model.ts
      - 基于
      t
      (TypeBox)定义的 schema 和类型
    • 共享工具类放在
      src/utils/*
      目录下。
  • 方法链式调用:推荐在Elysia实例上使用流式链式调用定义路由、守卫、插件。
  • 插件:通过
    .use()
    封装跨领域关注点(例如OpenAPI、JWT、CORS)。
  • 上下文纯净性:如果服务需要请求数据,在控制器层处理,仅将相关字段传入服务函数。

Feature Scaffolding Pattern

功能脚手架模式

When scaffolding a feature, generate:
  1. model.ts
    with
    t.Object(...)
    schemas and exported
    type
    aliases via
    typeof schema.static
    .
  2. service.ts
    with pure functions (or an
    abstract class
    of statics when no instance state is needed).
  3. index.ts
    that mounts the Elysia routes, applies
    guard()
    with shared validation, and returns typed responses.
搭建新功能时,生成以下文件:
  1. model.ts
    :包含
    t.Object(...)
    schema,通过
    typeof schema.static
    导出
    type
    别名。
  2. service.ts
    :包含纯函数(无需实例状态时也可以是静态方法的抽象类)。
  3. index.ts
    :挂载Elysia路由,应用共享校验的
    guard()
    ,返回带类型的响应。

Validation, Schemas & Types

校验、Schema与类型

Runtime Validation + Static Types

运行时校验 + 静态类型

  • Use
    import { t } from 'elysia'
    to define Body, Query, Params, Headers, Cookie, and Response schemas.
  • Derive TS types from
    typeof schema.static
    and export them (e.g.,
    export type SignInBody = typeof signInBody.static
    ).
  • Apply shared validation with
    .guard({ ... })
    . If combining guards, consider
    schema: 'standalone'
    to keep them independent.
  • Validate files by content: use
    fileType
    (magic number) when using standard schema systems.
  • Ensure response schemas are present for 2xx and error variants for strong end-to-end typing.
  • 使用
    import { t } from 'elysia'
    定义BodyQueryParamsHeadersCookieResponse schema。
  • typeof schema.static
    派生TS类型并导出(例如
    export type SignInBody = typeof signInBody.static
    )。
  • 通过
    .guard({ ... })
    应用共享校验。如果需要组合多个守卫,可使用
    schema: 'standalone'
    保持其独立性。
  • 校验文件内容:使用标准schema系统时通过
    fileType
    (魔数)校验。
  • 确保为2xx响应和错误变体都定义响应schema,实现强类型端到端校验。

Handler Schema Guidelines

处理程序Schema规范

When generating handlers:
  • Include the 3rd argument schema object with
    body/query/params/headers/cookie/response
    .
  • Don't parse body for GET/HEAD (Elysia follows HTTP spec).
  • Provide examples with
    t.Object
    ,
    t.Array
    ,
    t.Union
    ,
    t.Literal
    , file schemas, and show
    guard()
    for shared query/headers.
生成处理程序时:
  • 第三个参数传入包含
    body/query/params/headers/cookie/response
    的schema对象。
  • 不要为GET/HEAD请求解析body(Elysia遵循HTTP规范)。
  • 提供
    t.Object
    t.Array
    t.Union
    t.Literal
    、文件schema的示例,展示
    guard()
    用于共享query/headers的用法。

Error Handling & Response Shape

错误处理与响应格式

Centralized Error Management

集中式错误管理

  • Use
    .onError(({ code, error, path, request }) => { ... })
    on the app to map framework and custom errors to a uniform JSON shape (e.g.,
    { ok: false, error: { code, message, details } }
    ).
  • Prefer
    throw status(code, messageOrPayload)
    for error control flow that
    onError
    can catch. Note:
    return status(...)
    won't be caught by
    onError
    .
  • Validation errors: normalize them to a predictable JSON (array of issues) while hiding sensitive internals in production.
  • Include correlation ids (e.g.,
    x-request-id
    ) and log within
    onError
    . Avoid leaking stack traces in production.
  • For success responses, optionally wrap in
    { ok: true, data }
    for uniformity.
  • 在应用上使用
    .onError(({ code, error, path, request }) => { ... })
    将框架错误和自定义错误映射为统一JSON格式(例如
    { ok: false, error: { code, message, details } }
    )。
  • 错误控制流优先使用
    throw status(code, messageOrPayload)
    ,这样可以被
    onError
    捕获。注意:
    return status(...)
    不会被
    onError
    捕获。
  • 校验错误:将其格式化为可预测的JSON(问题数组),生产环境隐藏敏感内部信息。
  • onError
    中包含关联ID(例如
    x-request-id
    )并打日志。生产环境避免泄露堆栈信息。
  • 成功响应可选择包裹为
    { ok: true, data }
    格式保持统一性。

Error Plugin Structure

错误插件结构

When generating code, create:
  • src/plugins/error.ts
    that installs
    .onError(...)
    .
  • Optionally
    src/plugins/logging.ts
    to log in
    onResponse
    &
    onError
    .
生成代码时创建:
  • src/plugins/error.ts
    :注册
    .onError(...)
    逻辑。
  • 可选的
    src/plugins/logging.ts
    :在
    onResponse
    onError
    中打日志。

OpenAPI, Auth & Cross-cutting

OpenAPI、鉴权与跨领域功能

OpenAPI

OpenAPI

  • Add
    @elysiajs/openapi
    plugin and expose docs route (Scalar UI).
  • Keep response schemas accurate - OpenAPI derives from them.
  • If building SDKs, ensure routes are fully typed and examples provided.
  • 添加
    @elysiajs/openapi
    插件,暴露文档路由(Scalar UI)。
  • 保持响应schema准确,OpenAPI会基于其生成文档。
  • 如果需要构建SDK,确保路由全类型覆盖并提供示例。

Auth

鉴权

  • Use
    @elysiajs/jwt
    for JWT signing/verification, or integrate with your auth of choice.
  • Keep auth in a plugin that decorates context with
    user
    after verification.
  • Protect routes via
    .guard({ headers: t.Object({ authorization: t.String() }) })
    and verify bearer tokens before handlers.
  • 使用
    @elysiajs/jwt
    做JWT签名/校验,或集成你选择的其他鉴权方案。
  • 将鉴权逻辑封装在插件中,校验通过后为上下文添加
    user
    属性。
  • 通过
    .guard({ headers: t.Object({ authorization: t.String() }) })
    保护路由,在处理程序执行前校验Bearer令牌。

Cross-cutting Plugins

跨领域插件

  • Install
    @elysiajs/cors
    where needed.
  • Consider
    @elysiajs/server-timing
    and
    @elysiajs/opentelemetry
    for observability.
When scaffolding, generate
src/plugins/openapi.ts
,
src/plugins/auth.ts
, and wire them in
src/app.ts
.
  • 按需安装
    @elysiajs/cors
  • 可考虑使用
    @elysiajs/server-timing
    @elysiajs/opentelemetry
    实现可观测性。
搭建脚手架时生成
src/plugins/openapi.ts
src/plugins/auth.ts
,并在
src/app.ts
中引入注册。

Deploy, Performance & Docker

部署、性能与Docker

Production Deployment

生产部署

  • Cluster mode for multi-core: use a small launcher (
    index.ts
    ) that forks workers and imports
    server.ts
    per worker.
  • Prefer building with bundlers like Vite or esbuild for production deployments.
  • If compiling interferes with tracing (OpenTelemetry), avoid
    --minify
    or mark instrumented modules as
    --external
    .
  • Accept
    process.env.PORT
    (with fallback) and bind
    0.0.0.0
    for PaaS.
  • 多核场景使用集群模式:使用小型启动文件(
    index.ts
    )fork工作进程,每个工作进程导入
    server.ts
  • 生产部署优先使用Vite或esbuild等打包工具构建。
  • 如果编译影响链路追踪(OpenTelemetry),避免使用
    --minify
    或将被埋点的模块标记为
    --external
  • 读取
    process.env.PORT
    (带默认值),绑定
    0.0.0.0
    适配PaaS平台。

Docker

Docker

  • Build stage: use Node.js base image with pnpm.
  • Runtime: distroless base, copy binary,
    CMD ["./server"]
    .
  • 构建阶段:使用带pnpm的Node.js基础镜像。
  • 运行时:使用distroless基础镜像,复制二进制文件,
    CMD ["./server"]

Deployment Scaffolding

部署脚手架

When generating a deploy scaffold, include:
  • src/index.ts
    (cluster launcher),
    src/server.ts
    (app),
    Dockerfile
    (multi-stage), and build scripts.
生成部署脚手架时包含:
  • src/index.ts
    (集群启动文件)、
    src/server.ts
    (应用入口)、
    Dockerfile
    (多阶段构建)和构建脚本。

Testing

测试

Unit Tests

单元测试

  • Use
    vitest
    .
  • Import the app and use
    app.handle(new Request(url, options))
    to assert status/body/headers.
  • For service tests, call pure functions directly.
  • 使用
    vitest
  • 导入应用实例,使用
    app.handle(new Request(url, options))
    断言状态码/响应体/响应头。
  • 服务测试直接调用纯函数即可。

Test Examples to Include

测试示例需包含

  • Simple GET test returning text.
  • POST with
    body
    validation (both valid and invalid paths).
  • Authenticated route example using a mocked
    Authorization
    header.
  • Prefer small, focused tests per route and per service.
  • 简单GET请求返回文本的测试。
  • body
    校验的POST请求测试(合法和非法路径都覆盖)。
  • 使用模拟
    Authorization
    头的鉴权路由测试。
  • 每个路由和每个服务优先编写小型、聚焦的测试用例。

Quick Utilities

快速工具

Common Patterns

常用模式

  • App context: use
    .state()
    and
    .decorate()
    to add version info, helpers, etc., then read from
    { store, getDate }
    .
  • WebSocket endpoints via
    .ws()
    for simple real-time APIs.
  • Custom body parser with
    .onParse()
    for special content types.
  • 应用上下文:使用
    .state()
    .decorate()
    添加版本信息、工具方法等,后续从
    { store, getDate }
    中读取。
  • 通过
    .ws()
    定义WebSocket端点,实现简单的实时API。
  • 通过
    .onParse()
    自定义body解析器,处理特殊的Content-Type。

Validation Checklist

校验清单

Before finishing a task involving Elysia:
  • Feature structure follows
    model.ts
    ,
    service.ts
    ,
    index.ts
    pattern.
  • All handlers have proper schema definitions (body/query/params/response).
  • Error handling uses centralized
    .onError()
    plugin.
  • Response schemas are defined for OpenAPI generation.
  • Tests use
    app.handle(new Request(...))
    pattern.
  • Run type checks (
    pnpm run typecheck
    ) and tests (
    pnpm run test
    ).
For detailed patterns and code examples, see
references/patterns.md
.
完成涉及Elysia的任务前,请检查:
  • 功能结构遵循
    model.ts
    service.ts
    index.ts
    模式。
  • 所有处理程序都有正确的schema定义(body/query/params/response)。
  • 错误处理使用集中式
    .onError()
    插件。
  • 已定义响应schema用于OpenAPI生成。
  • 测试使用
    app.handle(new Request(...))
    模式。
  • 运行类型检查(
    pnpm run typecheck
    )和测试(
    pnpm run test
    )。
如需了解详细模式和代码示例,请查看
references/patterns.md