- Application Engineering
- June 19, 2024
Joey Nguyen
Table of Contents
Bun is a new Javascript runtime that was introduced in 2021 by its author, Jarred Sumner, following his frustrations with the speed of Node.js when developing a Next.js project. July 2022, the first beta of Bun was released. It immediately created a hype in JavaScript community. And the best news, Bun has its first official release, Bun 1.0 in September 2023.
Let’s look at some of its key value of Bun to see if it’s worth the hype.
What is Bun?
Bun is a best described as an all-in-one toolkit for JavaScript/TypeScript development. It’s written in Zig and powered by Apple’s JavascriptCore engine, which behind some Webkit browsers such as Safari, rather than infamous Chromium V8 engine, used by Node and Deno.
Bun is designed from the ground-up and aims to the key points below.
- Speed. Bun is designed for speed, it’s the best value of it. Bun is claimed that it outrun Node by 4 times.
- All-in-one toolkit. Bun helps you to escape from the hell of choosing tool chain for your next project by offer built-in package manager, bundler, monorepo tools, Typescript runtime and transpiler, test runner, JavaScript shell script, http and websocket server, even SQLite driver… all in one place, without any other installation.
- TypeScript & JSX support. Bun support Typescript and JSX out of the box. While Node’s developer still struggles between CommonJS and ES Module, bun support both, but encourage us to move forward with ESM.
- Node.js compatibility. Bun is not exactly a drop-in replacement for Node.js, but it tried to support many native Node modules, such as
node:process
,node:path
,node:fs
, etc…
How fast is Bun?
Let’s see how fast Bun is compared to Node.js
Firstly, let’s look at speed of both in the same framework.
Framework | Runtime | Average | Query | Body |
express | bun | 12,894.025 | 15,608.43 | 10,179.62 |
express | node | 5,111.12 | 5,102 | 5,120.24 |
Bun achieve 3x speed versus Node.js. But it’s not the fastest result.
In this benchmark, Bun uses express
HTTP API, which use node:http
API behind. Bun has different implementation of Web server, which use uWebsockets.js the fastest Node.js framework as its core. So, we will compare the fastest Node.js framework vs the fastest Bun framework.
Framework | Runtime | Average | Query | Body |
elysia | bun | 49,341.32 | 65,213.36 | 33,469.28 |
fastify | node | 14,271.595 | 17,890.78 | 10,652.41 |
Bun still out speed Node.js 3.5x.
Benchmark source code can be foundhere
Lastly, we will compare Bun and Node in a full-featured framework, NestJS. Yet this is not fair comparison, since NestJS use express as its core, which is much slower than uWebsockets in Bun. Unfortunately, Bun doesn’t have any framework on the same level as NestJS, so we will use NestJS for both Bun and Node.js.
Runtime | 1% | 2.5% | 50% | 97.5% | Average | Stdev | Min |
Bun | 21,103 | 21,103 | 30,863 | 31,695 | 28,657.6 | 3,957.17 | 21,090 |
Node.js | 7,607 | 7,607 | 12,959 | 13,583 | 12,079.6 | 2,252.75 | 7,605 |
Bun out speed Node.js 2.3x in this benchmark.
Benchmark source code can be foundhere
Create a simple Bun API
Now we will explore Bun by creating a simple application to demonstrate its features.
Create a simple application with Elysia
Install Bun, ignore if you already installed
curl https://bun.sh/install | bash
Create Elysia application.
bun create elysia your-appcd your-appbun dev # run app in development mode
Now you can access Elysia app viahttp://localhost:3000
Install database client
We choose Prisma as Database client
bun add -d prisma # -d flag indicates that this package is installed in devDependenciesbunx prisma init # bunx is similar to npx, but run in Bun environment
Add a User model to Prisma schema
generator client { provider = "prisma-client-js"}datasource db { provider = "postgresql" url = env("DATABASE_URL")}model User { id Int @id @default(autoincrement()) username String @unique password String}
Setup database connection in.env
file
DATABASE_URL="postgresql://<user>:<password>@localhost:5432/your_db"
Run migration
bunx prisma migrate dev
Add Prisma to Elysia
// ./src/index.tsimport { Elysia, t } from 'elysia'import { PrismaClient } from '@prisma/client'const prisma = new PrismaClient()const app = new Elysia()app.get('/users', async () => { return prisma.user.findMany();});app.post('/users', async ({ body }) => { return prisma.user.create({ data: { username: body.username, password: await Bun.password.hash(body.password) // Bun.hash is a built-in function to hash password, using Argon2 } });}, { // Elysia schema validation using Typebox body: t.Object({ username: t.String(), password: t.String({ minLength: 8 }) })});app.get('/users/:username', async ({ params: { username } }) => { return prisma.user.findUnique({ where: { username } });});app.listen(3000);
Bonus: Add Elysia Swagger module
bun add @elysiajs/swagger
import { swagger } from '@elysiajs/swagger'// add this line to ./src/index.ts, after `const app = new Elysia()`app.use(swagger())
Now you can access Swagger UI viahttp://localhost:3000/swagger
Run application
bun dev
Now accesshttp://localhost:3000/swagger
to see your API documentation and test your API.
Create a simple application with NestJS
It’s not different from creating a NestJS application using Bun versus Node.js. Just follow NestJS getting started and run application with Bun:
bun --bun nest start
Notice that--bun
flag is required for Bun to force NestJS CLI not invokingnode
command at run time.
You can find example of NestJS application with Bunhere.
Final thoughts
As Bun 1.0 released, Bun is gaining interest from Web Development community. Its ecosystem is growing extremely fast. It still can’t compare to 13 years old Node.js but it promises to be a game-changer by its features and superior performance.
Different than Deno, with Bun, we almost don’t need to change the way things work, just a little bit of changes. Likenpm install
, is nowbun install
. The best way to describe this point is you can run a simple NestJS application with Bun without changing a single line of code.
All-in-one toolkit also an interesting point that makes developer experiences more enjoyable, since we have a lot of tools need to install in our source base, such aswebpack
,pnpm
,esbuild
,jest
… Now only Bun’s needed.
But the real question is:
Is Bun ready for production?
Unfortunately, no. At least, not right now. But in next few months, it will be.
I experience some unsolved issues while developing a project with Bun. Still a lot of runtime issues, that throwSEGFAULT
that cannot be caught, a lot of them reported in Github issues and are not resolved yet.
But, again, Bun is very promising thing for JavaScript development. It just a matter of time until Bun becomes more stable. Bun seems to be getting closer every step to take Node’s crown. I believe investing in Bun is worth to consider at the moment.
Suggested Article
Joey Nguyen
Leave a Comment
Suggested Article
GitOps: Best Practices for the Real World
Byrupali1520 10th September 2024 Cloud Engineering
Version Control Best Practices
Byrupali1520 10th September 2024 Cloud Engineering
AWS Insights: Unlocking the Power of Cloud Monitoring and Optimization
Byrupali1520 10th September 2024 Cloud Engineering