DEV Community

Alex Spinov
Alex Spinov

Posted on

Elysia Has a Free API You Should Know About

Elysia is the fastest Bun web framework, and its type system does things no other framework can.

End-to-End Type Safety

import { Elysia, t } from 'elysia'

const app = new Elysia()
  .get('/api/users', async () => {
    return db.user.findMany()
  })
  .post('/api/users', async ({ body }) => {
    return db.user.create({ data: body })
  }, {
    body: t.Object({
      name: t.String({ minLength: 1 }),
      email: t.String({ format: 'email' }),
      age: t.Optional(t.Number({ minimum: 0 }))
    })
  })
  .listen(3000)

// Type is inferred automatically — no codegen needed
type App = typeof app
Enter fullscreen mode Exit fullscreen mode

Eden — Type-Safe Client

// On the client — full autocompletion, zero codegen
import { treaty } from '@elysiajs/eden'
import type { App } from './server'

const api = treaty<App>('localhost:3000')

const { data: users } = await api.api.users.get()
//    ^? User[]  — fully typed!

const { data: newUser } = await api.api.users.post({
  name: 'John',
  email: 'john@test.com'
})
Enter fullscreen mode Exit fullscreen mode

Plugin System

const authPlugin = new Elysia({ name: 'auth' })
  .derive(({ headers }) => {
    const token = headers.authorization?.replace('Bearer ', '')
    return { user: token ? verifyJWT(token) : null }
  })
  .macro(({ onBeforeHandle }) => ({
    requireAuth(enabled: boolean) {
      if (enabled) onBeforeHandle(({ user, error }) => {
        if (!user) return error(401, 'Unauthorized')
      })
    }
  }))

const app = new Elysia()
  .use(authPlugin)
  .get('/api/profile', ({ user }) => user, { requireAuth: true })
Enter fullscreen mode Exit fullscreen mode

Lifecycle Hooks

new Elysia()
  .onBeforeHandle(({ request }) => {
    console.log(`${request.method} ${request.url}`)
  })
  .onAfterHandle(({ response, set }) => {
    set.headers['x-powered-by'] = 'Elysia'
    return response
  })
  .onError(({ error, code }) => {
    if (code === 'VALIDATION') return { error: error.message }
    return { error: 'Internal Server Error' }
  })
Enter fullscreen mode Exit fullscreen mode

Real-World Use Case

A team needed a tRPC-like experience but without React dependency. Elysia + Eden gave them end-to-end type safety with zero codegen, and Bun's speed meant their API handled 50K req/sec on a single $5 server. Their entire backend is 300 lines of TypeScript.

Elysia is what happens when you build a framework for Bun from day one.


Build Smarter Data Pipelines

Need to scrape websites, extract APIs, or automate data collection? Check out my ready-to-use scrapers on Apify — no coding required.

Custom scraping solution? Email me at spinov001@gmail.com — fast turnaround, fair prices.

Top comments (0)