Telerik blogs

Learn what Elysia.js is, how it works with the Bun runtime and how we can use it to build APIs. We’ll also explore its core features and performance approach.

Elysia.js is a TypeScript backend framework built with performance and developer experience in mind. In this article, we’ll cover what Elysia.js is, how it works with the Bun runtime, and how we can use it to build APIs. We’ll also explore Elysia’s core features and performance approach.

To put these concepts into practice, we’ll use Elysia.js to build a simple Task Manager API that lets us create, view, update, and delete tasks. Finally, we’ll look at the advantages and limitations of Elysia.js to help you decide when it might be a good fit for your project.

Prerequisites

This article assumes you have a basic understanding of backend development, APIs, HTTP methods, and JavaScript or TypeScript.

What Is Elysia.js?

According to its documentation, Elysia is a TypeScript backend framework focused on developer experience, performance and end-to-end type safety.

It’s designed to be fast, lightweight and developer-friendly. The name comes from Elysium, the paradise of Greek mythology, often described as a place of perfect happiness.

Why Fast APIs Matter in Modern Development

In any industry that relies on software, an API’s performance can directly affect how users experience an application.

Imagine a business serving thousands of customers online within minutes. If its API takes too long to process requests and return responses, users will have a poor experience. Over time, this can hurt the business’s revenue and reputation, as users may leave for a competitor that responds faster.

As applications grow, handling more requests efficiently becomes very important. Developers need tools and architectures that help them build responsive, scalable APIs, and this is where Elysia.js comes in as one of the newer frameworks designed to solve this problem.

Elysia.js and Bun

Like other JavaScript backend frameworks, Elysia.js helps you build servers and APIs. What makes it different is that it’s optimized for Bun. While it works best with Bun, it can also run in other environments, such as Node.js.

Overview of the Framework

In this section, we’ll look at the major areas involved in building a backend and the tools Elysia provides to handle each of them.

  • Routing: Elysia lets developers define endpoints and associate them with HTTP methods such as GET, POST, PUT, PATCH and DELETE. We’ll see how to use these later in the article.
  • Request handling: Elysia provides route handlers and a request context, which give your application access to incoming data such as the request body, query parameters and headers.
  • Response handling: Elysia makes it easy to send data back to the client. You can return values directly from route handlers and control the response with status codes, headers and cookies.
  • Data validation: A common backend practice is making sure incoming data has the expected structure. Elysia handles this with Elysia.t schemas and support for Standard Schema.
  • Type safety: Elysia infers types directly from your schemas and integrates closely with TypeScript, which keeps your types consistent across your application.
  • Request lifecycle: Elysia provides lifecycle hooks such as onBeforeHandle, onAfterHandle and onError that let you control what happens before and after a handler runs.
  • Plugins: Elysia’s plugin system lets developers package functionality into reusable pieces instead of putting everything inside the main application.
  • API documentation: Elysia can use the schemas you’ve already defined to generate documentation for your API automatically.

How Elysia Leverages the Bun Runtime

When you build an API with Elysia, the work is split between two layers. Elysia provides the framework layer, which includes the features covered earlier, such as routing, request and response handling, data validation and type safety. Bun provides the runtime layer, which executes the application and supplies underlying capabilities such as HTTP serving.

Although Elysia can run in other environments, it is designed and optimized specifically around Bun, which gives it an advantage when the two work together. For example, when running on Bun, Elysia can use Bun’s native routing through the routes option in Bun.serve, as well as Bun’s native WebSocket implementation.

Getting Started

First, we need to install Bun. The installation steps vary slightly depending on your operating system.

macOS and Linux

Open your terminal and run the following command:

curl -fsSL https://bun.com/install | bash

Once it finishes, close and reopen your terminal, then check that Bun installed correctly:

bun --version

If you see a version number such as 1.x.x, Bun was installed successfully.

Windows

Bun requires Windows 10 version 1809 or later. Open PowerShell and run:

powershell -c "irm [bun.com/install.ps1|iex](http://bun.com/install.ps1%7Ciex)"

When the installation is complete, restart your terminal and run bun --version to confirm it worked.

Setting Up Elysia.js

Now that Bun is installed, the next step is to set up an Elysia project. Run the following command in your terminal:

bun create elysia my-app

Once the project is created, move into the project folder:

cd my-app

Before creating your first API, start the development server:

bun dev

Building a Project with Elysia.js

A Task Manager API is a backend application that lets us manage tasks through API requests. A client can send requests to create a new task, retrieve existing tasks, update a task when its status changes or delete a task that’s no longer needed.

In this project:

  • Each task will have an id, title, description and completed status.
  • The API will support GET (retrieve tasks), POST (create a task), PUT (update a task) and DELETE (delete a task) requests.

We won’t make the storage system too complicated. Instead of using an external database, we will store our tasks in an in-memory array. This keeps the project simple and allows us to focus on how the API works. One thing to keep in mind is that the data will only exist while the server is running. When the server restarts, all stored tasks will be lost.

For this demo, we’ll keep things simple by defining all of our routes and handlers in a single file. The main application code will live in the src/[index.ts](http://index.ts) file. As we build the Task Manager API, we will be adding the routes for creating, retrieving, updating and deleting tasks to this file.

Step-by-Step Setup

Before we start building the API, let’s take a quick look at how everything will work.

The client will send a request to the API built with Elysia.js. Depending on the route being called, the API will retrieve, add, update or delete information from our in-memory task data.

Our task data will look something like this:

let tasks = [
  {
    id: 1,
    title: 'Learn Elysia.js',
    description: 'Understand the basics of building APIs with Elysia',
    completed: false
  }
]

Now, let’s create the project. Run the following command in your terminal to create a new Elysia.js project called task-app:

bun create elysia task-app

Once the project has been created, run this command to move into the project directory:

cd task-app

Then run this command to start the development server:

bun dev

With the project running, let’s start building the routes for our Task Manager API.

Creating Routes (GET, POST, PUT, DELETE)

We’ll begin with the GET routes, which allow us to retrieve task data.

Route to Retrieve All Tasks (GET)

.get('/tasks', () => {
  return tasks
})

This route returns all the tasks currently stored in our in-memory tasks array. When a client sends a GET request to /tasks, the API responds with the full list of available tasks.

Route to Retrieve a Single Task (GET)

.get('/tasks/:id', ({ params }) => {
  const task = tasks.find(task => task.id === Number(params.id))
  return task
})

This route returns a single task based on its id. For example, if a client sends a request to /tasks/1, Elysia makes the value 1 available through params.id. We then use the find() method to search through the tasks array and return the task whose id matches the one provided in the request.

Create a Task (POST)

.post('/tasks', ({ body }) => {
  const task = {
    id: tasks.length + 1,
    ...body
  }

  tasks.push(task)

  return task
})

This route creates a new task and adds it to our tasks array. The body contains the task data sent by the client. For simplicity, we generated the id using the current length of the tasks array plus one. This works well enough for our demo, but in a production application, IDs would usually be generated by a database or another more reliable ID-generation strategy. After creating the task, we add it to the array and return the newly created task in the response.

Update a Task (PUT)

.put('/tasks/:id', ({ params, body }) => {
  const index = tasks.findIndex(
    task => task.id === Number(params.id)
  )

  if (index === -1) {
    return { message: 'Task not found' }
  }

  tasks[index] = {
    ...tasks[index],
    ...body
  }

  return tasks[index]
})

This route updates an existing task using its id. First, we search for the position of the task whose id matches the value provided in the route parameter. Since params.id is received as a string, we convert it to a number before comparing it with the task IDs in our array.

If no matching task is found, we return a message letting the client know that the task could not be found. If the task exists, we update it by combining the existing task data with the new values provided in the request body. Finally, we return the updated task in the response.

Delete a Task (DELETE)

.delete('/tasks/:id', ({ params }) => {
  const index = tasks.findIndex(
    task => task.id === Number(params.id)
  )

  if (index === -1) {
    return { message: 'Task not found' }
  }

  const deletedTask = tasks.splice(index, 1)

  return deletedTask[0]
})

This route deletes a task from our tasks array using its id. We start by finding the task that matches the id provided in the route parameter.

If no matching task is found, we return a message letting the client know that the task does not exist.

If the task is found, we use the splice() method to remove it from the array.

At this point, we have the basic CRUD operations working, but our API currently trusts whatever data the client sends. What happens if the client sends the wrong data type, leaves out a required field or provides data in an unexpected format? This is where validation comes in.

Adding Validation

Validation helps us control the kind of data our backend expects to receive from the client. It allows us to check incoming data before it is processed by the route handler.

Elysia allows us to define these expectations using the t schema builder. We can import IT directly from the elysia package:

import { Elysia, t } from 'elysia'

We can then use t to describe the structure and data types we expect:

body: t.Object({
  title: t.String(),
  description: t.String(),
  completed: t.Boolean()
})

Validation is helpful whenever a route expects data from the client, such as request bodies, route parameters or query parameters. Let’s validate the body of the POST request.

import { Elysia, t } from 'elysia'

new Elysia()
  .post('/tasks', ({ body }) => {
    const task = {
      id: tasks.length + 1,
      ...body
    }

    tasks.push(task)

    return task
  }, {
    body: t.Object({
      title: t.String(),
      description: t.String(),
      completed: t.Boolean()
    })
  })

In the code above, the client sends an object in the request body, and Elysia checks that object against the schema defined for the route. If all the fields match the expected structure and data types, the request is passed to the handler and the task is created. If the data does not match the schema, the request fails validation before the handler runs.

Here is an example of data that would fail validation:

{
  "title": 123,
  "description": "Practice creating routes with Elysia",
  "completed": "false"
}

Elysia will reject this request because the data does not match the schema we defined. The title field is expected to be a string, but it has been given a number. The completed field is expected to be a boolean, but "false" is a string because it is wrapped in quotation marks.

Since the request body does not match the expected data types, Elysia stops the request before the route handler is executed.

Testing the Endpoints

Let’s test our endpoints to make sure they behave the way we expect. For this example, we’ll use curl from the command line.

Run the following command in your terminal to start the Elysia development server:

bun dev

Once the server is running, the API will be available at http://localhost:3000.

Getting All Tasks

To retrieve all the tasks, send a GET request to the /tasks endpoint:

curl.exe http://127.0.0.1:3000/tasks

As shown below, this request returns all the tasks currently stored in the application.

Retrieve all tasks

Creating a Task

To create a new task, send a POST request to the /tasks endpoint and include the task data in the request body.

If the task data is stored in a file called task.json, you can run the following command:

curl.exe -i -X POST "http://127.0.0.1:3000/tasks" -H "Content-Type: application/json" --data-binary "@task.json"

The Content-Type: application/json header tells the API that the request body contains JSON data, while --data-binary "@task.json" reads the data directly from the task.json file.

If the request is successful, the API returns the newly created task, including its generated id.

Creating a task

Getting a Single Task

To retrieve a specific task, include its id in the request URL:

curl.exe -i "http://127.0.0.1:3000/tasks/2"

In this example, 2 is the ID of the task we want to retrieve. If a task with that ID exists, the API returns that task in the response.

Retrieve a specific task

Updating a Task

To update an existing task, send a PUT request and include the task id in the URL:

curl.exe -i -X PUT "http://127.0.0.1:3000/tasks/2" -H "Content-Type: application/json" --data-binary "@task.json"

In this example, 2 is the ID of the task we want to update, while task.json contains the new task data.

If the task exists and the request is successful, the API returns the updated task in the response.

Update an existing task

Testing Validation

Finally, let’s test what happens when invalid data is sent to the API. For example, our schema expects title to be a string and completed to be a boolean. If the client sends data that does not match these expected types, Elysia rejects the request before it reaches the route handler.

As shown below, the API returns a 422 Unprocessable Entity response, indicating that the request data failed validation.

Image showing failed validation

These tests confirm that the main endpoints of our Task Manager API are working as expected. They also show that our validation schema successfully prevents requests with invalid data from being processed by the route handlers.

We’ve covered the basics we need to get started with Elysia. However, there are a couple of other features worth knowing about as you continue building with the framework: plugins and TypeScript support.

Performance

Another reason developers may consider using Elysia is performance. Knowing how to write code is important, but understanding performance matters too. In a backend application, performance can affect how quickly a request is processed and how long it takes for the client to receive a response.

It’s also important to remember that the performance of an application does not depend only on the programming language or framework being used. Other factors such as hardware, runtime versions, endpoint complexity, database operations, external services, network latency and the number of concurrent requests can all affect how an application performs.

Elysia.js and Edge Computing

Another factor that can affect application performance is where the application is deployed. This is where edge computing comes in.

Edge computing means running application logic closer to the users making requests. In a traditional setup, a backend application may run on a server in one location. A user’s request has to travel to that server and then back again with the response. If the user is far from the server, this can increase network latency. Edge computing helps reduce this distance by allowing parts of an application to run closer to the user, which can make responses feel faster.

Elysia’s lightweight and performance-focused design can make it suitable for environments that support edge or serverless-style deployment. However, using Elysia does not automatically make an application an edge application. That depends on where the application is deployed.

If an Elysia application runs on a traditional server in one region, requests still travel to that server. If it is deployed on infrastructure that supports edge execution, application logic can run closer to users. So, Elysia can fit well into edge environments, but the actual benefits of edge computing depend on the deployment platform and how the application is configured.

What Makes Elysia.js Fast?

Elysia is designed with performance in mind. Some of the ideas that contribute to this include efficient routing, low framework overhead, its schema-driven approach, and its close integration with Bun.

Let’s look at each of these in more detail.

  • Efficient routing: Elysia is designed to perform route matching efficiently so that incoming requests can be directed to the appropriate handler with minimal unnecessary work. This becomes increasingly important as an application grows and begins to contain more routes.
  • Low framework overhead: Another factor that can affect performance is the amount of work a framework performs before your application logic runs. When a request reaches the server, the framework needs to process it before passing it to the appropriate handler. If a framework performs a large amount of additional work for every request, that can introduce extra overhead. Elysia is designed to keep this overhead relatively small, allowing requests to move through the framework efficiently before reaching the application logic.
  • Schema-driven approach: By defining the structure of the data an application expects, Elysia has more information about the requests and responses it is working with. The same schemas can also provide TypeScript type inference. This means Elysia can combine runtime validation and type information using the same schema, reducing unnecessary duplication in the code.
  • Optimized for Bun: Elysia is built with Bun in mind, allowing it to take advantage of features provided by the Bun runtime. Because of this close integration, Elysia can benefit from Bun’s approach to running JavaScript and TypeScript server applications.

Advantages and Limitations

Let’s look at some of Elysia’s advantages and a few things developers should consider before choosing it for a project.

Where Elysia.js Excels

- **TypeScript support:** One of Elysia.js’s main strengths is its TypeScript support. As we saw earlier, Elysia can use schemas for both runtime validation and TypeScript type inference. This means we can define the structure of our data once and reuse that information throughout the application instead of repeating the same type definitions in multiple places.
- **Performance:** Another advantage is its focus on performance. Elysia is designed with low overhead in mind and is closely optimized for Bun. Combined with features such as routing, validation, plugins and TypeScript support, this gives developers a lightweight framework for building modern backend applications without introducing unnecessary complexity.
- **Application structure and reusability:** Elysia also gives developers flexibility in how an application is structured. Features such as plugins make it easier to separate functionality and reuse it across different parts of the application. This becomes very useful as a project grows and begins to include more routes, schemas, authentication logic, and other shared functionality.

Things Developers Should Consider

Elysia.js may not be the right choice for every project, and here are a few factors worth considering:

- **Runtime considerations:** Elysia is closely associated with Bun, so if your team already has a large application built around Node.js and its ecosystem, adopting Elysia may require some additional planning. Moving to a different runtime can affect tooling, dependencies, deployment and existing development workflows.
- **Ecosystem and community:** Compared with more established frameworks such as Express, Elysia has a smaller ecosystem and community. This means you may not always find the same number of tutorials, packages, examples or developers with experience solving specific problems with the framework.
- **Real-world performance:** It is also important not to choose Elysia based on benchmark results alone. As we discussed earlier, the performance of a real application depends on many factors, including database queries, external API calls, network latency, business logic and the overall design of the application.

Elysia.js provides several useful advantages. However, choosing a framework should always depend on the needs of the project.

Before deciding to use Elysia, it is worth considering factors such as your team’s experience, the ecosystem and tooling you depend on, your deployment environment and the overall requirements of the application.

Conclusion

In this article, we looked at what Elysia.js is, how it works with Bun, and how to build a simple API with it. The best way to get comfortable with Elysia.js is to experiment with it yourself. Start with a small API, add a few routes, try validation and explore plugins as your project grows.

This will give you a better sense of how Elysia.js works in practice and whether it fits the kind of backend applications you want to build.


About the Author

Christian Nwamba

Chris Nwamba is a Senior Developer Advocate at AWS focusing on AWS Amplify. He is also a teacher with years of experience building products and communities.

Related Posts

Comments

Comments are disabled in preview mode.