> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/honojs/hono/llms.txt
> Use this file to discover all available pages before exploring further.

# Bun

> API reference for the Bun adapter

The Bun adapter provides utilities for running Hono applications on Bun, including static file serving, SSG support, WebSocket handling, and server utilities.

## Import

```ts theme={null}
import { 
  serveStatic, 
  toSSG, 
  bunFileSystemModule,
  upgradeWebSocket,
  websocket,
  createBunWebSocket,
  getConnInfo,
  getBunServer
} from 'hono/bun'
import type { BunWebSocketData, BunWebSocketHandler } from 'hono/bun'
```

## Functions

### serveStatic()

Middleware for serving static files from the local file system in Bun.

```ts theme={null}
function serveStatic<E extends Env = Env>(
  options: ServeStaticOptions<E>
): MiddlewareHandler
```

#### Parameters

* `options.root` - `string` (optional) - Root directory path (default: `'.'`)
* `options.path` - `string` (optional) - Base path for static files
* `options.rewriteRequestPath` - `(path: string) => string` (optional) - Function to rewrite request paths
* Additional options from base `ServeStaticOptions`

#### Example

```ts theme={null}
import { Hono } from 'hono'
import { serveStatic } from 'hono/bun'

const app = new Hono()

app.use('/static/*', serveStatic({ root: './public' }))
app.use('/favicon.ico', serveStatic({ path: './public/favicon.ico' }))

export default app
```

### upgradeWebSocket()

Helper function to upgrade HTTP connections to WebSocket connections in Bun.

```ts theme={null}
function upgradeWebSocket<T>(
  createEvents: (c: Context) => WSEvents
): MiddlewareHandler
```

#### Parameters

* `createEvents` - Function that receives context and returns WebSocket event handlers

#### Example

```ts theme={null}
import { Hono } from 'hono'
import { upgradeWebSocket } from 'hono/bun'

const app = new Hono()

app.get(
  '/ws',
  upgradeWebSocket((c) => {
    return {
      onOpen: (evt, ws) => {
        console.log('Connection opened')
      },
      onMessage: (event, ws) => {
        console.log(`Message: ${event.data}`)
        ws.send('Hello from Bun!')
      },
      onClose: (evt, ws) => {
        console.log('Connection closed')
      },
    }
  })
)

export default {
  port: 3000,
  fetch: app.fetch,
  websocket,  // Required for WebSocket support
}
```

### websocket

Bun WebSocket handler that must be exported alongside your app for WebSocket functionality.

```ts theme={null}
const websocket: BunWebSocketHandler<BunWebSocketData>
```

#### Example

```ts theme={null}
import { Hono } from 'hono'
import { upgradeWebSocket, websocket } from 'hono/bun'

const app = new Hono()

app.get('/ws', upgradeWebSocket((c) => ({ /* ... */ })))

export default {
  port: 3000,
  fetch: app.fetch,
  websocket,  // Export the websocket handler
}
```

### createBunWebSocket()

<Warning>
  `createBunWebSocket` is deprecated. Import `upgradeWebSocket` and `websocket` directly from `hono/bun` instead.
</Warning>

Legacy function to create a Bun WebSocket handler.

```ts theme={null}
function createBunWebSocket<T>(): {
  upgradeWebSocket: UpgradeWebSocket<T>
  websocket: BunWebSocketHandler<BunWebSocketData>
}
```

### toSSG()

<Note>
  `toSSG` is an experimental feature. The API might be changed.
</Note>

Generates static HTML files from your Hono application (Static Site Generation).

```ts theme={null}
function toSSG(
  app: Hono,
  options?: ToSSGOptions
): Promise<ToSSGResult>
```

#### Example

```ts theme={null}
import { Hono } from 'hono'
import { toSSG } from 'hono/bun'

const app = new Hono()

app.get('/', (c) => c.html('<h1>Home</h1>'))
app.get('/about', (c) => c.html('<h1>About</h1>'))

await toSSG(app, { dir: './dist' })
```

### bunFileSystemModule

<Note>
  `bunFileSystemModule` is an experimental feature. The API might be changed.
</Note>

File system module implementation for Bun, used by `toSSG`.

```ts theme={null}
const bunFileSystemModule: FileSystemModule
```

### getConnInfo()

Extracts connection information from the Bun request.

```ts theme={null}
function getConnInfo(c: Context): ConnInfo
```

#### Returns

```ts theme={null}
interface ConnInfo {
  remote: {
    address?: string      // Client IP address
    addressType?: string  // 'IPv4' or 'IPv6'
    port?: number        // Client port
  }
}
```

#### Example

```ts theme={null}
import { Hono } from 'hono'
import { getConnInfo } from 'hono/bun'

const app = new Hono()

app.get('/', (c) => {
  const info = getConnInfo(c)
  return c.json({
    ip: info.remote.address,
    type: info.remote.addressType,
    port: info.remote.port
  })
})

export default {
  port: 3000,
  fetch: app.fetch,
}
```

### getBunServer()

Gets the Bun server instance from the context.

```ts theme={null}
function getBunServer<T>(c: Context): T | undefined
```

#### Returns

The Bun server object, or `undefined` if not available.

#### Example

```ts theme={null}
import { Hono } from 'hono'
import { getBunServer } from 'hono/bun'

const app = new Hono()

app.get('/server-info', (c) => {
  const server = getBunServer(c)
  if (!server) {
    return c.text('Server info not available', 500)
  }
  return c.json({
    port: server.port,
    hostname: server.hostname
  })
})

export default app
```

## Types

### BunWebSocketData

Internal data structure for WebSocket connections.

```ts theme={null}
interface BunWebSocketData {
  events: WSEvents
  url: URL
  protocol: string
}
```

### BunWebSocketHandler

Bun-specific WebSocket handler interface.

```ts theme={null}
interface BunWebSocketHandler<T> {
  open(ws: BunServerWebSocket<T>): void
  close(ws: BunServerWebSocket<T>, code?: number, reason?: string): void
  message(ws: BunServerWebSocket<T>, message: string | { buffer: ArrayBufferLike }): void
}
```

## Platform-Specific Notes

* Bun uses `Bun.file()` for optimized file serving
* Connection info is retrieved via `server.requestIP()`
* WebSocket support requires exporting the `websocket` handler alongside `fetch`
* The server instance must be passed in the second argument of `app.fetch()` for `getConnInfo` and WebSocket to work
* Bun provides excellent performance for static file serving

## Running Your Application

### Basic Server

```ts theme={null}
// server.ts
import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => c.text('Hello Bun!'))

export default {
  port: 3000,
  fetch: app.fetch,
}
```

```bash theme={null}
bun run server.ts
```

### With WebSocket

```ts theme={null}
import { Hono } from 'hono'
import { upgradeWebSocket, websocket } from 'hono/bun'

const app = new Hono()

app.get('/ws', upgradeWebSocket((c) => ({
  onMessage: (evt, ws) => ws.send(`Echo: ${evt.data}`),
})))

export default {
  port: 3000,
  fetch: app.fetch,
  websocket,  // Required for WebSocket
}
```

## See Also

* [Bun Documentation](https://bun.sh/docs)
* [Bun WebSocket API](https://bun.sh/docs/api/websockets)
* [Bun.serve](https://bun.sh/docs/api/http)
