How to Build High-Performance APIs with Elysia and Bun
Elysia is a fast, ergonomic web framework built specifically for the Bun runtime. It combines Bun’s native speed with an elegant API inspired by Express and Fastify. This tutorial walks you through creating a simple REST API using Elysia, including routes, validation, and middleware.
Before you start, ensure you have Bun installed (version 1.0.0 or later). You can verify with bun --version. Create a new directory and run bun init to scaffold a project.
Setting Up Your Elysia Project
Install Elysia using Bun’s package manager:
bun add elysia
Create an index.ts file and import Elysia:
import { Elysia } from 'elysia';
const app = new Elysia();
app.listen(3000, () => {
console.log('🔥 Elysia running on http://localhost:3000');
});
Run your server with bun run index.ts. You now have a working Elysia server.
Defining Routes and Handling Requests
Add routes using familiar HTTP methods. Elysia uses a chainable API:
app.get('/', () => 'Hello Bun!');
app.post('/data', ({ body }) => {
return { received: body };
});
Access route parameters with square brackets:
app.get('/user/:id', ({ params: { id } }) => `User ${id}`);
Validation and Middleware
Elysia integrates with @elysiajs/validator for schema validation. Install it:
bun add @elysiajs/validator
Use it to validate request bodies:
import { validator } from '@elysiajs/validator';
app.post('/signup',
validator({
body: t.Object({
email: t.String({ format: 'email' }),
password: t.String({ minLength: 8 })
})
}),
({ body }) => `Welcome ${body.email}!`
);
For middleware, simply call .use() with a function that modifies request or set:
app.use((app) => app.onBeforeHandle(({ request }) => {
console.log(`Request: ${request.method}`);
}));
Running in Production
Elysia supports hot reloading with bun --watch. For production, use bun build --target=bun index.ts to compile a single binary. Then run the output:
bun run dist/index.js
Deploy to any Bun‑compatible host (e.g., Fly.io, Railway).
Elysia combines Bun’s blistering speed with a developer‑friendly API. Start small, add validation and middleware as needed, and you’ll have a production‑ready API in minutes.