Starting with Bun : The Fastest JavaScript Runtime

Starting with Bun : The Fastest JavaScript Runtime

What is Bun may ask.

Bun offers a comprehensive toolkit tailored for JavaScript and TypeScript applications, encapsulated within a singular executable named 'bun'.

Central to its design is the Bun runtime, an optimized JavaScript runtime crafted to seamlessly substitute Node.js. Engineered in Zig and anchored by JavaScriptCore, it significantly trims down both startup durations and memory consumption.

As they claim

  • Bun is a fast JavaScript package
  • Bun is a fast JavaScript package manager
  • Bun is a fast JavaScript bundler

Here's a brief summary of article:

  • Nature of Bun: Bun is multifaceted, acting as a rapid JavaScript package, package manager, and bundler.

  • Compatibility: Currently, Bun is exclusively supported on macOS, Linux, and WSL. For Windows users, a Linux virtual machine setup is necessary.

  • Installation: Users can easily install Bun using the provided curl command. There are visual aids in the form of screenshots to assist users throughout the installation process.

  • Building a Server: The article offers a step-by-step guide on creating a basic HTTP server using Bun's native API. The server is initiated on port 3000 and displays a message "Bun!" when accessed.

  • Script Execution: Like Node.js, Bun can run "scripts" from the package.json file. The article provides a sample package.json setup for reference.

  • Using Express with Bun: The integration of Bun with the popular web application framework, Express, is explored. A basic server setup using Express is provided, which displays a "Hello World!" message.

  • Server-side Rendering with React: Delving deeper into more advanced applications, the article showcases how to perform server-side rendering of a React component using Bun. This section provides a React component sample, and how it can be rendered on the server side and sent as pre-rendered HTML elements.

  • Conclusion: While Bun is still in its early phases of development, it shows considerable potential as a tool in the JavaScript domain.

The article concludes with further reading suggestions, providing resources on various applications and perspectives on Bun.

Installation

Let's install this bad boy. Unfortunately, Bun is supported only on macOS, Linux, and WSL. If you have Windows machine then you have to install Linux virtual machine as I did.

Run this command curl -fsSL https://bun.sh/install | bash ubuntu terminal

Let's write a simple HTTP server using the built-in Bun.serve API. First, create a fresh directory.

Run bun init to scaffold a new project. It's an interactive tool; for this tutorial, just press enter to accept the default answer for each prompt.

Bun init

Run a file

Open index.ts and paste the following code snippet, which implements a simple HTTP server with Bun.serve.

const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Bun!");
  },
});

console.log(`Listening on http://localhost:${server.port} ...`);

Run the file from your shell:

bun index.ts

Output:

Listening on http://localhost:3000 ...

Bun index.ts

Visit http://localhost:3000 to test the server. You should see a simple page that says "Bun!".

Bun index.ts

Run a script

Just like Node.js , Bun can also execute "scripts" from your package.json. Add the following script:

{
  "name": "firstbun",
  "module": "index.ts",
  "type": "module",
  "scripts": {
    "start": "bun run index.ts"
  },
  "devDependencies": {
    "bun-types": "latest"
  },
  "peerDependencies": {
    "typescript": "^5.0.0"
  }
}

Then run it with bun run start.

bun run start

$ bun run index.ts

Listening on http://localhost:3000...

Build an HTTP server using Express and Bun

But first lets switch to javascript instead of typescipt (personal preference).

Remove tsconfig.json and rename index.ts to index.js

Express and other major Node.js HTTP libraries should work out of the box. Bun implements the node:http and node:https modules that these libraries rely on.

import express from "express";

const app = express();
const port = 8080;

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.listen(port, () => {
  console.log(`Listening on port ${port}...`);
});

Server-side render (SSR) a React component with Bun

Now for the fun part. Lets use the react and jsx syntax to send some pre rendered HTML elements

First create a react component:

helloworldcomp.jsx


export function MessageComponent({message}) {
  return (
    <h1>
      {message}
    </h1>
  );
}

Then on our server file index.js

import express from "express";
import ReactDOMServer from "react-dom/server"
import { MessageComponent } from "./helloworldcomp";


const app = express();
const port = 3000;

app.get("/", async (req, res) => {
  const htmlstring = await ReactDOMServer.renderToString(<MessageComponent message='Hello World!' />);
  res.send(htmlstring);
});

app.listen(port, () => {
  console.log(`Listening on port ${port}...`);
});

alt text

That's it for now. Bun is really on early stages but seems promising.

Thank you for your time,

Eneas

Other sources:

How to Write an Express-like API Using Bun.js

Server-side render (SSR) a React component with Bun

Bun: The Next Big Thing in Javascript

Basics of React server-side rendering with Express.js

More to read