💻 Programming

Elysia

A TypeScript web framework for Bun

📖 Detailed Explanation

Elysia is a TypeScript web framework optimized for the Bun runtime, pursuing type safety and extreme performance at the same time. It emerged in 2023 and is growing rapidly, boasting processing speeds up to 18 times faster than Express.js.

Elysia's most distinctive feature is End-to-End Type Safety. API schemas defined on the server are automatically type-inferred all the way to the client, fundamentally preventing type mismatch problems between the frontend and backend. It is similar to tRPC but is provided in the form of a REST API.

The plugin system lets you modularize and reuse functionality. Official plugins provide automatic Swagger documentation generation, JWT authentication, CORS handling, GraphQL integration, and more, and you can create custom plugins to easily share common logic across an entire project.

In practice, Elysia is well suited for high-performance API servers, microservices, and real-time applications. Combined with Bun's native SQLite, file I/O, and bundling features, you can quickly build full-stack applications without separate tools.

💻 Code Example

// 1. 기본 Elysia 서버 설정
import { Elysia, t } from 'elysia';
import { swagger } from '@elysiajs/swagger';
import { jwt } from '@elysiajs/jwt';

// 사용자 타입 정의
interface User {
    id: number;
    name: string;
    email: string;
}

const users: User[] = [];

const app = new Elysia()
    // Swagger 문서 자동 생성
    .use(swagger({
        documentation: {
            info: { title: 'Elysia API', version: '1.0.0' }
        }
    }))
    // JWT 인증 플러그인
    .use(jwt({
        name: 'jwt',
        secret: process.env.JWT_SECRET || 'super-secret-key'
    }))
    // 전역 에러 핸들러
    .onError(({ code, error }) => {
        console.error(`[${code}] ${error.message}`);
        return { error: error.message };
    });

// 2. CRUD API 라우트 정의 (타입 안전)
app.group('/api/users', (app) =>
    app
        // 사용자 목록 조회
        .get('/', () => users, {
            detail: { summary: '모든 사용자 조회' }
        })
        // 사용자 생성 (입력 검증 포함)
        .post('/', ({ body }) => {
            const newUser: User = {
                id: users.length + 1,
                ...body
            };
            users.push(newUser);
            return newUser;
        }, {
            body: t.Object({
                name: t.String({ minLength: 2 }),
                email: t.String({ format: 'email' })
            }),
            detail: { summary: '새 사용자 생성' }
        })
        // 특정 사용자 조회
        .get('/:id', ({ params: { id }, error }) => {
            const user = users.find(u => u.id === Number(id));
            if (!user) return error(404, '사용자를 찾을 수 없습니다');
            return user;
        })
);

// 3. 서버 시작
app.listen(3000, () => {
    console.log('🦊 Elysia 서버가 http://localhost:3000 에서 실행 중');
    console.log('📖 Swagger 문서: http://localhost:3000/swagger');
});

🗣️ Say It Like This in Practice

💬 In a Meeting
"I think we should build this microservice with Elysia. Thanks to the performance of the Bun runtime and End-to-End type safety, we can reduce API spec sync issues with the frontend team. Swagger documentation is also generated automatically."
💬 In an Interview
"Unlike Express.js or Fastify, Elysia is optimized for Bun, and it supports both TypeBox-based runtime schema validation and compile-time type inference. The plugin system lets you cleanly separate common functionality such as authentication and logging."
💬 In a code review
"Using t.Object for the body schema is good, but please wrap the optional fields here with t.Optional(). Also, if you unify the error responses into a consistent format, it will be easier to handle them on the frontend."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Attempting to run on Node.js

Elysia is a Bun-only framework. It does not run on Node.js, so be sure to run it with `bun run` or `bun dev`. When migrating an existing Node.js project, you must first check dependency compatibility.

❌
Accessing body without a schema

If you access the request body without defining a body schema, you lose type safety. Always define a schema with t.Object(), and clearly distinguish between required and optional fields.

✅
Separate common logic into plugins

Use .use() and .derive() to separate common logic such as authentication, logging, and error handling into plugins. This improves code reusability and makes testing easier.

🔗 Related Terms

📚 Learn More