ElysiaJS Documentation

repository·main·Indexed 41 days ago

https://github.com/elysiajs/documentation

A high-performance, ergonomic web framework optimized for Bun and WinterTC compliant. Features include automatic type inference, schema validation via Elysia.t and Standard Schema libraries (Zod, Valibot, etc.), automatic OpenAPI documentation generation, and AOT compilation for optimized performance. Supports deployment on Bun, Node.js, Deno, and Cloudflare Workers.

Tokens
135.7K
Snippets
515
Records
606
Agent score
50%

What's inside ElysiaJS

  1. Overview of Elysia 1.3 performance improvements

    main

    Elysia 1.3 focuses on refinement and performance optimizations rather than new features. Key improvements include:

    • Exact Mirror: A drop-in replacement for TypeBox normalization that is significantly faster (up to 500x for small objects).
    • Dual Router Strategy: Automatically attempts to use Bun's native router (if available) for dynamic routes, falling back to Elysia's router.
    • Standalone Validator: Allows merging schemas in guards instead of overriding them.
    • Reduced Type Instantiation: Up to 60% improvement in type inference speed and reduced memory usage for large-scale applications.
    • Route Registration & Instance Optimization: Significant reductions in memory usage (up to 5.6x for routes, 10x for instances) and faster startup/plugin creation times.
    • Sucrose Cache: Reduces re-computation by caching compiled routes using checksums.
  2. Summary of Elysia 0.8 Changes and Improvements

    main

    Elysia 0.8 introduced several performance and API refinements:

    Improvements:

    • Static Query Analysis: Automatic query inference for faster lookups.
    • Video Streaming: Automatic content-range header for File and Blob.
    • Memory Optimization: Reuses lifecycle event return values to reduce memory pressure.
    • Validation: Errors are now returned as structured JSON.
    • Plugin Updates: Official plugins like Static, HTML, and CORS have been optimized using Elysia.headers and MapResponse.

    Breaking Changes & API Changes:

    • afterHandle no longer triggers early return.
    • Validation response format changed from text to JSON.
    • derive is now differentiated from decorator['request'] as decorator['derive'].
    • derive no longer shows inferred types in onRequest.
    • Removed headers, path, and derive from PreContext.
  3. Elysia Core Features and Type Safety

    main

    Elysia is an ergonomic TypeScript framework designed for high performance and end-to-end type safety. It provides first-class support for various services like Swagger, WebSocket, and tRPC. Key features include:

    • End-to-end Type Safety: Automatically infer types for parameters, bodies, queries, and responses.
    • Schema Validation: Supports multiple validation libraries including TypeBox (t), Zod, Valibot, ArkType, and Effect.
    • Macros: Extend Elysia functionality by defining custom lifecycle hooks and properties.
    • Eden Integration: Use @elysia/eden to create type-safe clients that mirror your server's API structure.
    import { Elysia, t } from 'elysia'
    
    new Elysia()
      .get('/user/:id', ({ params }) => {
        // params.id is automatically typed
        return `User ${params.id}`
      })
      .listen(3000)
  4. Notable improvements in Elysia 0.6

    main

    Elysia 0.6 introduced several performance and developer experience improvements:

    • Custom Errors: Added an error field to the Elysia type system to allow adding custom error messages.
    • Cloudflare Workers Support: Added support for Cloudflare Workers via Dynamic Mode (including ENV support).
    • Automatic Mapping: afterHandle now automatically maps values.
    • Performance: Uses bun build to target the Bun environment, resulting in a 5-10% performance boost.
    • Plugin Optimization: Deduplicated inline lifecycles when using plugin registration.
    • Routing: Added support for setting a prefix and implemented recursive path typing.
    • Type System: Improved type checking speed and resolved recursive schema collision issues that caused infinite types.
  5. Explore ElysiaJS community plugins

    main

    ElysiaJS has a rich ecosystem of community-maintained plugins that extend its functionality. These plugins cover various categories such as:

    • Authentication & Security: Lucia Auth, Elysia Clerk, OAuth 2.0 (with 42+ providers), Basic Auth, Elysia Helmet (security headers), Elysia XSS (sanitization), and ModernCSRF.
    • Routing & Framework Integration: Elysia FSR (file-system routing), Autoload (filesystem router for Eden), Nuxt integration, Remix support, and Vite server plugins.
    • Logging & Observability: Logysia, Logestic, Logger (pino-based), Logify, LogTape, Apitally (metrics/traces), and Sentry (error capturing).
    • Data & Serialization: Msgpack, XML, Elysia Protobuf, and Elysia Drizzle Schema.
    • Utilities: Rate Limit, Elysia Compression, Elysia IP, Elysia env (type-safe env vars), and Elysia Background (background tasks).

    Always check the specific repository of a plugin for installation instructions and compatibility.

  6. Explore complementary projects and templates for Elysia

    main

    The Elysia ecosystem includes external tools and templates to accelerate development:

    • prismabox: A generator for TypeBox schemas based on your database models. It is designed to work seamlessly with Elysia's type-safe validation.
    • ElysiaTemplate: An MVC backend template that provides auto-routing and middleware capabilities.
  7. Explore official Elysia plugins

    main

    The Elysia team maintains several official plugins to handle common web server requirements. These include:

    • Bearer: Automatically retrieves Bearer authentication tokens.
    • CORS: Sets up Cross-origin resource sharing (CORS).
    • Cron: Sets up cron jobs for scheduled tasks.
    • Eden: Provides an end-to-end type-safe client for Elysia.
    • GraphQL Apollo: Enables running Apollo GraphQL on Elysia.
    • GraphQL Yoga: Enables running GraphQL Yoga on Elysia.
    • HTML: Handles HTML responses.
    • JWT: Provides authentication using JSON Web Tokens (JWTs).
    • OpenAPI: Generates OpenAPI documentation for your API.
    • OpenTelemetry: Adds support for OpenTelemetry observability.
    • Server Timing: Uses the Server-Timing API to audit performance bottlenecks.
    • Static: Serves static files and folders.
  8. What is a Macro in ElysiaJS?

    main

    A Macro is a powerful abstraction that functions similarly to a function but with control over lifecycle events, schemas, and context, all while maintaining full type safety. Once a macro is defined using the .macro() method, it becomes available as a property in the route options object. Macros are useful for implementing complex logic like authorization layers or injecting data into the request context.

    import { Elysia } from 'elysia'
    
    const plugin = new Elysia({ name: 'plugin' })
        .macro({
            hi: (word: string) => ({
                beforeHandle() {
                    console.log(word)
                }
            })
        })
    
    const app = new Elysia()
        .use(plugin)
        .get('/', () => 'hi', {
            hi: 'Elysia' // Activates the 'hi' macro with 'Elysia' as the argument
        })
  9. What is a Handler in ElysiaJS

    main

    A Handler is a function that accepts an HTTP request and returns a response. Handlers are registered using methods like Elysia.get or Elysia.post.

    Handlers can be defined as functions or as inline values. Using an inline value (like a string or a file) allows Elysia to compile the response ahead of time, optimizing performance for static resources. Note that providing an inline value is not a cache; static resource values, headers, and status can still be mutated dynamically using lifecycle hooks.

    import { Elysia } from 'elysia'
    
    new Elysia()
        // The function `() => 'hello world'` is a handler
        .get('/', () => 'hello world')
        .listen(3000)
    
    // Inline value for static resources
    new Elysia()
        .get('/', 'Hello Elysia')
        .listen(3000)
  10. What is a Handler in Elysia

    main

    A Handler is a resource or a route function responsible for sending data back to the client. In Elysia, a handler can be defined in two ways:

    1. A function: A callback that executes when the route is matched.
    2. A literal value: A static value (like a string) that is returned directly. This is particularly useful for serving static resources like files.

    Example of a function handler:

    import { Elysia } from 'elysia'
    
    new Elysia()
        .get('/', () => 'hello world')
        .listen(3000)

    Example of a literal value handler:

    import { Elysia } from 'elysia'
    
    new Elysia()
        .get('/', 'hello world')
        .listen(3000)
    import { Elysia } from 'elysia'
    
    new Elysia()
        .get('/', () => 'hello world')
        .listen(3000)
  11. What is Elysia

    main

    Elysia is a high-performance, ergonomic TypeScript backend framework designed with developer experience and type safety in mind. Key characteristics include:

    • Performance: High-speed execution comparable to Golang.
    • Type Safety: Extraordinary TypeScript support with type soundness and end-to-end type safety (similar to tRPC).
    • OpenAPI: Built around OpenAPI standards from the ground up.
    • Web Standards: Uses standard Web APIs, allowing it to run on various runtimes including Bun, Deno, Node.js, and Cloudflare Workers.
  12. What is Eden and how does it provide end-to-end type safety?

    main

    Eden is an RPC-like client that connects an Elysia server to a client with end-to-end type safety using TypeScript's type inference instead of code generation. This allows changes made to the server's types to be instantly reflected on the client, providing auto-completion and type enforcement.

    Eden is lightweight (under 2KB) and consists of two main modules:

    1. Eden Treaty (Recommended): An object-like RPC client providing full type support, auto-completion, and type-narrowed error handling.
    2. Eden Fetch: A fetch-like client for developers who prefer standard fetch syntax.

    Note: Unlike Eden Treaty, Eden Fetch does not provide a WebSocket implementation for the Elysia server.