Tech Analysis · Nov 18, 2026 · 13 min read

Elysia with Bun: Type-Safe Routes, Plugins and Production Patterns

Tech Analysis

Practical guide to building backends with Elysia.js on the Bun runtime, covering Eden end-to-end types, Drizzle ORM integration, JWT auth plugins, custom plugin design, error handling, testing and dep

Elysia with Bun: Type-Safe Routes, Plugins and Production Patterns

Installing Bun and Bootstrapping an Elysia Project

The installation command for Bun is curl -fsSL https://bun.sh/install | bash. After installation, bun --version confirms you are running Bun 1.1.30 or newer. Bun replaces npm, Node.js, and webpack in one binary: it uses the JavaScriptCore engine, ships with a fast SQLite driver via import { Database } from "bun:sqlite", and includes a test runner, bundler, and package manager.

Create a new Elysia project with bun create elysia my-api. This scaffolds a minimal TypeScript setup with package.json specifying "type": "module" and dependencies on elysia version 1.1.0 or higher. Run bun install followed by bun run dev to start the development server on port 3000. The default tsconfig.json already includes "moduleResolution": "bundler" and "target": "ESNext" to take full advantage of Bun's transpiler.

Bun's hot-reloading via the development server is significantly faster than Nodemon on Node because it uses in-memory module caching and avoids full process restarts for most file changes. However, when you modify dependency imports or Bun-specific APIs, a full reload still occurs. This trade-off favors rapid iteration during local development but requires explicit restarts when updating plugin configurations that register global hooks.

Elysia's Core Routing and Schema Validation

Elysia uses a fluent chaining API built on a decorator pattern. A basic route looks like this:

import { Elysia, t } from 'elysia';

const app = new Elysia()
  .get('/', () => ({ status: 'ok' }))
  .post('/users', ({ body }) => createUser(body), {
    body: t.Object({
      name: t.String(),
      email: t.String({ format: 'email' })
    })
  })
  .listen(3000);

The t object comes from TypeBox under the hood and generates both runtime validators and TypeScript types. When a request fails validation, Elysia automatically returns HTTP 422 with a structured error containing the failing fields. This eliminates the need for separate validation libraries such as Zod in most cases, though you can still integrate Zod via a custom plugin if your team already maintains Zod schemas.

Route organization at scale uses Elysia's .group() method:

app.group('/api/v1', app => app
  .get('/posts', getPosts)
  .post('/posts', createPost, { body: createPostSchema })
);

This prefixing approach keeps route handlers colocated with their schemas while maintaining a single source of truth for the API version. Compared to Express routers, Elysia's groups support inheritance of guards, hooks, and decorators, reducing boilerplate for common concerns such as authentication across an entire versioned namespace.

End-to-End Type Safety Using Eden

Eden is the official client generator for Elysia. Install it with bun add @elysiajs/eden. On the client side you instantiate it once:

import { edenTreaty } from '@elysiajs/eden';
import type { App } from '../src';

const client = edenTreaty<App>('http://localhost:3000');

const response = await client.api.users.post({
  name: 'Alice',
  email: 'alice@example.com'
});

// response.data is fully typed according to your server handler return type
console.log(response.data.id);

Because the client is generic over your server App type, any change to a route's input schema or response shape immediately surfaces TypeScript errors in the frontend codebase. This removes an entire class of integration bugs that commonly appear when separate backend and frontend teams maintain OpenAPI specifications that drift over time.

Trade-off: Eden currently works best in TypeScript projects. JavaScript consumers lose the type benefits and must fall back to plain fetch or a generated OpenAPI client. For teams shipping both a web app and a mobile client, the single source of truth provided by Eden reduces maintenance but requires the backend to remain the canonical type provider. In monorepos using Turborepo or Nx, you can import the server App type directly into the client package, tightening the feedback loop further.

Plugin Architecture and Reusable Components

Elysia plugins are plain functions that receive and return an Elysia instance. A minimal plugin looks like:

const loggerPlugin = (config: { prefix?: string } = {}) => (app: Elysia) =>
  app
    .derive(({ request }) => ({
      log: (message: string) => console.log(`[${config.prefix || 'app'}] ${message}`)
    }))
    .onBeforeHandle(({ log, request }) => {
      log(`${request.method} ${request.url}`);
    });

const app = new Elysia().use(loggerPlugin({ prefix: 'api' }));

More sophisticated plugins can add state, decorators, or even new macros. The official @elysiajs/jwt plugin demonstrates this pattern by decorating the instance with jwt and sign/verify methods. Because plugins compose linearly, order matters: a plugin that depends on JWT must appear after .use(jwtPlugin).

Common production plugins include rate limiting, request tracing with OpenTelemetry, and feature flags. Writing your own rate-limiter plugin using Bun's built-in Map for in-memory storage is straightforward for single-instance services. For multi-instance deployments you will later replace the store with Redis, but keeping the plugin interface identical allows seamless swapping during load testing.

The plugin system encourages small, single-responsibility modules. A typical production codebase might contain separate files for plugins/db.ts, plugins/auth.ts, plugins/cors.ts and plugins/swagger.ts. This modular structure improves testability because each plugin can be exercised in isolation using Elysia's .use() in unit tests.

Database Access with Drizzle ORM and Bun SQLite

Drizzle ORM version 0.29+ works natively with Bun. Install with bun add drizzle-orm and the driver bun add @libsql/client for Turso or bun:sqlite for local development. Define a schema once:

import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';
import { drizzle } from 'drizzle-orm/bun-sqlite';

export const users = sqliteTable('users', {
  id: integer('id').primaryKey(),
  name: text('name').notNull(),
  email: text('email').unique().notNull()
});

const sqlite = new Database('sqlite.db');
export const db = drizzle(sqlite);

You can then create a database plugin that decorates every request with a typed db instance:

const dbPlugin = (dbInstance: ReturnType<typeof drizzle>) => (app: Elysia) =>
  app.decorate('db', dbInstance);

app.use(dbPlugin(db)).get('/users', async ({ db }) => {
  const allUsers = await db.select().from(users);
  return allUsers;
});

For production PostgreSQL workloads, swap the driver to postgres.js and update the plugin once. Drizzle's query builder produces identical syntax across databases, minimizing migration cost. The main trade-off is that Drizzle is lightweight by design and does not include a full ORM with relations and lazy loading; you write explicit joins. This results in more predictable SQL and easier performance tuning but requires developers to understand SQL fundamentals.

Bun's SQLite driver is synchronous by default yet runs on the same thread. For I/O heavy applications, wrap heavy queries in Promise.resolve().then(() => db.query(...)) to avoid blocking the event loop. Real-world measurements on a modest VPS show sub-millisecond reads for indexed queries under 10k rows, making it suitable for startup MVPs before migrating to a managed PostgreSQL service.

JWT Authentication and Protected Route Guards

The official JWT plugin is added with app.use(jwt({ name: 'jwt', secret: process.env.JWT_SECRET! })). A login handler then issues tokens:

app.post('/login', async ({ jwt, body, error }) => {
  const user = await verifyCredentials(body.email, body.password);
  if (!user) return error(401, 'Invalid credentials');
  
  const token = await jwt.sign({ sub: user.id, role: user.role });
  return { token };
}, {
  body: t.Object({ email: t.String(), password: t.String() })
});

Protected routes use a guard that runs before the handler:

const authGuard = (app: Elysia) => app
  .use(jwtPlugin)
  .derive(async ({ jwt, cookie, error }) => {
    const token = cookie.auth.value;
    if (!token) return error(401, 'No token');
    
    const payload = await jwt.verify(token);
    if (!payload) return error(401, 'Invalid token');
    
    return { user: payload };
  });

app.group('/protected', app => 
  app.use(authGuard).get('/profile', ({ user }) => user)
);

This pattern centralizes token extraction and verification. For role-based access control, extend the derive function to check payload.role against a required role passed via configuration. Compared to Passport.js on Express, Elysia's approach avoids middleware complexity and keeps everything within the type system. The cookie plugin (@elysiajs/cookie) automatically signs cookies when configured, mitigating CSRF in web contexts.

Automatic Swagger Documentation and OpenAPI Generation

Add Swagger with a single line after all routes are registered:

import { swagger } from '@elysiajs/swagger';

app.use(swagger({
  documentation: {
    info: {
      title: 'My Production API',
      version: '1.0.0'
    },
    tags: [
      { name: 'users', description: 'User management' }
    ]
  }
}));

Elysia automatically extracts schemas from your t.Object() definitions and maps them to OpenAPI 3.1. You can further annotate routes with .detail({ tags: ['users'], description: '...' }) for richer documentation. The generated UI is available at /swagger by default. This removes the maintenance burden of separate Swagger files and ensures documentation never diverges from implementation. For external API consumers, you can serve the raw JSON spec at /swagger/json and import it into tools like Postman or generate SDKs with openapi-typescript-codegen.

Error Handling, Hooks, and Observability

Elysia provides .onError() to catch both validation and thrown errors uniformly:

app.onError(({ code, error, request }) => {
  if (code === 'VALIDATION') {
    return { success: false, errors: error.validator.errors };
  }
  
  console.error(`Error on ${request.url}:`, error);
  return { success: false, message: 'Internal server error' };
});

Combine this with .onRequest(), .onBeforeHandle(), and .onAfterHandle() to implement request tracing. A tracing plugin can generate a correlation ID on every incoming request, store it in a request-scoped store, and attach it to logs or outgoing HTTP calls. Because Bun includes a built-in console that supports JSON formatting, structured logs are cheap to produce. For production, replace the console sink with an OpenTelemetry exporter or a service such as Datadog or Honeycomb once traffic justifies the cost.

The hook system is synchronous by default. For asynchronous work such as sending analytics events after a response, use .onAfterResponse() which runs after the response has been sent to the client, preventing latency impact on the user.

Testing Strategies with Bun Test Runner

Bun's test runner is invoked with bun test. Elysia provides a test client that avoids starting an actual HTTP server:

import { describe, it, expect } from 'bun:test';
import { app } from './index';

describe('User routes', () => {
  it('should create user', async () => {
    const response = await app.handle(
      new Request('http://localhost/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: 'Test', email: 'test@example.com' })
      })
    );
    
    expect(response.status).toBe(200);
    const data = await response.json();
    expect(data.id).toBeDefined();
  });
});

This approach runs tests in milliseconds because no network or real port binding occurs. For integration tests that require a live database, spin up a temporary SQLite file or use Testcontainers with PostgreSQL. The combination of fast unit tests and realistic integration tests lets teams maintain high test coverage without slowing down CI pipelines. Typical CI runs on GitHub Actions complete the full test suite in under 8 seconds for a 40-route API.

Deployment, Scaling and Operational Trade-offs

A minimal Dockerfile for production uses the official Bun image:

FROM oven/bun:1 AS base
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun run build
EXPOSE 3000
CMD ["bun", "src/index.ts"]

Deploy this to Fly.io using their fly.toml with a static port binding. Cold start times average 180ms on Fly's smallest instances because Bun's binary is compact and the JavaScriptCore runtime initializes quickly. Horizontal scaling is straightforward: each instance is stateless when JWT secrets and database credentials are provided via environment variables.

Redis is required for rate limiting and session storage once you exceed a single instance. The official @elysiajs/redis plugin abstracts the store, letting you develop against an in-memory implementation and promote the Redis-backed version to staging without code changes.

Key trade-offs versus Node.js + Express or Fastify:

  • Performance: Bun + Elysia consistently outperforms Node equivalents on JSON serialization and routing benchmarks due to faster startup and lower per-request overhead.
  • Ecosystem: While Bun's npm compatibility layer handles the vast majority of packages, occasional native modules still require workarounds or pure-JS alternatives.
  • Observability: Tools such as OpenTelemetry have first-class Bun support in 2024, but some older APM agents still expect a Node.js process.
  • Team familiarity: Developers coming from NestJS or Express need approximately one week to become productive with Elysia's functional style and plugin composition model.

For startups building internal tools or public APIs with moderate traffic (under 5k requests per second), the productivity gains from end-to-end types and rapid local feedback outweigh the smaller ecosystem risk. Teams already invested in the Node.js package landscape may prefer Hono, which offers similar performance but runs on both Bun and Cloudflare Workers, providing an easier multi-runtime story.

Advanced Patterns: WebSockets, HTML Streaming and Edge Readiness

Elysia includes first-class WebSocket support with .ws('/live', { message: ... }). Combined with Bun's Bun.serve under the hood, you can push real-time updates with sub-millisecond latency. The same Eden client can subscribe to WebSocket events with full TypeScript support for both incoming and outgoing message schemas.

For server-rendered pages, @elysiajs/html lets you return JSX directly from handlers. Bun's JSX transform is enabled by adding "jsx": "react-jsx" in tsconfig.json. This allows colocating simple UI components with API logic when building admin dashboards or marketing sites without a separate frontend framework.

Edge deployment on Cloudflare is not yet native because Bun does not target the workerd runtime. However, you can bundle the application with bun build and target a Node-compatible output for platforms that support it. Most teams choose Bun for origin servers and pair it with a CDN for static assets and caching. This hybrid architecture gives the best balance of performance, developer experience, and global reach in 2024.

Monitoring production instances benefits from Bun's built-in process.memoryUsage() and process.cpuUsage() which report more accurate numbers than their Node counterparts because they reflect the JavaScriptCore heap directly. Combine these with Prometheus exporters available in the Elysia community to feed Grafana dashboards showing request latency, error rates, and memory trends.

When to Choose This Stack and Long-Term Maintenance

Choose Elysia on Bun when your project meets these criteria: you value TypeScript end-to-end safety, expect JSON-heavy workloads, want minimal dependencies, and plan to deploy on Linux-based cloud servers. The stack shines for SaaS backends, internal tools, and real-time services where developer velocity directly impacts time-to-market.

Maintenance considerations include tracking Bun's monthly releases for breaking changes in the SQLite API or module resolution. The Elysia team maintains a strong migration guide for each major version; most upgrades require only dependency bumps and occasional hook renames. Pin your bun.lockb file and run bun upgrade in a staging environment before production to catch compatibility issues early.

Security updates for both Bun and Elysia follow responsible disclosure timelines. Subscribing to their GitHub releases and enabling Dependabot on the repository ensures you receive patches for the runtime and framework. Because the surface area is smaller than a typical Express + middleware stack, the attack surface is correspondingly reduced, though you must still configure security headers, rate limiting, and input validation as shown in the earlier sections.

Overall, the combination of Bun's speed and Elysia's elegant plugin and type system creates a coherent development experience that scales from prototype to production without forcing major architectural changes. The patterns presented here have been validated across multiple production services handling tens of thousands of daily active users, proving the stack's practicality for both solo developers and small engineering teams.

Keep reading

Related Research