Back to H3

Bun

docs/3.adapters/bun.md

1.15.111.1 KB
Original Source

Bun

Run your h3 apps with Bun

In order to run h3 apps in Bun, use the Web Adapter.

[!NOTE] Alternatively you can use Node.js adapter as Bun is fully compatible with Node.js API!

Usage

Create app entry:

js
import { createApp, defineEventHandler } from "h3";

export const app = createApp();

app.use(defineEventHandler(() => "Hello world!"));

Create Bun server entry:

js
import { toWebHandler } from "h3";
import { app } from "./app.mjs";

const server = Bun.serve({
  port: 3000,
  fetch: toWebHandler(app),
});

Now, your can run Bun server:

bash
bun --bun ./server.mjs

WebSocket support

:read-more{to="https://crossws.unjs.io/adapters/bun"}

ts
import wsAdapter from "crossws/adapters/bun";

const { websocket, handleUpgrade } = wsAdapter(app.websocket);

const handler = toWebHandler(app);

const server = Bun.serve({
  port: 3000,
  websocket,
  fetch(req, server) {
    if (await handleUpgrade(req, server)) {
      return;
    }
    return handler(req);
  },
});