Relevant source files
The following files were used as context for generating this wiki page:
- src/adapter/bun/index.ts
- src/adapter/bun/websocket.ts
- src/adapter/bun/serve-static.ts
- src/helper/streaming/sse.ts
- src/adapter/cloudflare-workers/index.ts
- src/adapter/bun/conninfo.ts
- src/adapter/cloudflare-pages/handler.ts
- src/adapter/deno/websocket.ts
- src/adapter/deno/index.ts
- src/hono-base.ts
- src/adapter/cloudflare-pages/index.ts
- src/adapter/cloudflare-workers/websocket.ts
- src/adapter/deno/serve-static.ts
- src/adapter/bun/server.ts
- src/adapter/lambda-edge/handler.ts
- src/helper/streaming/stream.ts
- src/adapter/vercel/index.ts
- src/middleware/serve-static/index.ts
- package.json
- src/helper/websocket/index.ts
- src/adapter/service-worker/index.ts
- src/adapter/cloudflare-workers/serve-static-module.ts
- src/adapter/netlify/handler.ts
- src/adapter/bun/ssg.ts
- src/helper/adapter/index.ts
- runtime-tests/workerd/index.ts
- src/context.ts
- src/adapter/vercel/handler.ts
- src/adapter/service-worker/handler.ts
- src/adapter/cloudflare-workers/serve-static.ts
Overview
The Bun adapter package exposes public barrel exports including serveStatic, bunFileSystemModule, toSSG, createBunWebSocket, upgradeWebSocket, websocket, getConnInfo, and getBunServer.
Sources: src/adapter/bun/index.ts:1-11
The adapter retrieves the running Bun server instance from Execution Context via getBunServer, accessing underlying request IP functions and WebSocket server upgrade capabilities.
Sources: src/adapter/bun/server.ts:1-14, src/adapter/bun/websocket.ts:48-72, src/adapter/bun/conninfo.ts:10-28
Static asset middleware integrates with Static File Serving through Bun.file and Node.js filesystem helpers to check paths, determine directories, and serve content.
Sources: src/adapter/bun/serve-static.ts:1-31
Connection metadata extraction parses server remote address and socket details into standardized IP structures using Bun's requestIP API.
Sources: src/adapter/bun/conninfo.ts:10-43
Static site generation is supported via experimental filesystem bindings and toSSG adapters that interface directly with Bun's native write methods.
Sources: src/adapter/bun/ssg.ts:1-27
Entry point and module exports
Public Module Surface
The Bun adapter package exports functions, modules, and type definitions that bridge Hono with the Bun runtime environment. These modules include static asset serving, SSG integration, WebSocket management, connection information extraction, and server instance retrieval. Sources: src/adapter/bun/index.ts:1-11
| Export Symbol | Export Type | Source Module | Purpose |
|---|---|---|---|
serveStatic | Function | ./serve-static | Serves static assets using Bun file system APIs |
bunFileSystemModule | Object | ./ssg | Provides filesystem bindings for static site generation |
toSSG | Function | ./ssg | Generates static site outputs via Bun filesystem integration |
createBunWebSocket | Function | ./websocket | Creates a Bun-specific WebSocket handler and upgrade pair |
upgradeWebSocket | Function | ./websocket | Upgrades HTTP requests to WebSockets on Bun |
websocket | Object | ./websocket | WebSocket configuration helper object |
BunWebSocketData | Type | ./websocket | Type definition for Bun WebSocket state data |
BunWebSocketHandler | Type | ./websocket | Type definition for Bun WebSocket event handlers |
getConnInfo | Function | ./conninfo | Extracts remote connection metadata from requests |
getBunServer | Function | ./server | Retrieves the running Bun server instance from execution context |
Sources: src/adapter/bun/index.ts:1-11
Note
All exports from src/adapter/bun/index.ts are re-exported at the package root to provide direct access to Bun-specific features without deep import paths.
Sources: src/adapter/bun/index.ts:1-11
Native Bun server reference management
Server Retrieval via getBunServer
The getBunServer helper function extracts the active Bun server instance from an Execution Context Context object. It accepts a generic type parameter T representing the specific Bun server type and inspects the context environment bindings (c.env) to locate the server reference.
Sources: src/adapter/bun/server.ts:1-14
export const getBunServer = <T>(c: Context): T | undefined =>
('server' in c.env ? c.env.server : c.env) as T | undefinedSources: src/adapter/bun/server.ts:1-14
Note
The function checks whether the server property exists directly on c.env. If present, it returns c.env.server; otherwise, it falls back to treating c.env itself as the server instance, casting the result to type T | undefined.
Sources: src/adapter/bun/server.ts:13-14
Static asset resolution via Bun.file
Middleware Integration and Native Handlers
The Bun adapter provides a specialized serveStatic middleware function that wraps Hono's base static asset handler (baseServeStatic) from Static File Serving. It injects Bun-specific file system primitives (Bun.file) and Node.js fs/promises utilities to resolve file existence, query directory status, and join paths.
Sources: src/adapter/bun/serve-static.ts:1-31
export const serveStatic = <E extends Env = Env>(
options: ServeStaticOptions<E> = {}
): MiddlewareHandler => {
return async function serveStatic(c, next) {
const getContent = async (path: string) => {
// @ts-ignore
const file = Bun.file(path)
return (await file.exists()) ? file : null
}
const isDir = async (path: string) => {
let isDir
try {
const stats = await stat(path)
isDir = stats.isDirectory()
} catch {}
return isDir
}
return baseServeStatic({
...options,
getContent,
join,
isDir,
})(c, next)
}
}Sources: src/adapter/bun/serve-static.ts:8-31
Note
The getContent closure calls Bun.file(path) and evaluates file.exists(), returning the Bun file handle if present or null otherwise. Directory checking (isDir) uses node:fs/promises stat wrapped in a try/catch block to safely handle missing paths without throwing unhandled exceptions.
Sources: src/adapter/bun/serve-static.ts:12-24
Connection info extraction
Server Request Metadata and Remote Address Mapping
The Bun adapter implements connection metadata extraction through the getConnInfo function, which conforms to the GetConnInfo helper signature. It retrieves the underlying Bun server instance via getBunServer with typed constraints for requestIP, ensuring that runtime execution environments supply the required second argument to fetch.
Sources: src/adapter/bun/conninfo.ts:10-42
export const getConnInfo: GetConnInfo = (c: Context) => {
const server = getBunServer<{
requestIP?: (req: Request) => {
address: string
family: string
port: number
} | null
}>(c)
if (!server) {
throw new TypeError('env has to include the 2nd argument of fetch.')
}
if (typeof server.requestIP !== 'function') {
throw new TypeError('server.requestIP is not a function.')
}
// https://bun.sh/docs/runtime/http/server#server-requestip-request
// Returns null for closed requests or Unix domain sockets.
const info = server.requestIP(c.req.raw)
if (!info) {
return {
remote: {},
}
}
return {
remote: {
address: info.address,
addressType: info.family === 'IPv6' || info.family === 'IPv4' ? info.family : undefined,
port: info.port,
},
}Sources: src/adapter/bun/conninfo.ts:10-42
Warning
If c.env lacks a server reference or server.requestIP is not a function, getConnInfo throws a TypeError. This occurs when requests are processed without binding the Bun server instance to the execution context.
Sources: src/adapter/bun/conninfo.ts:19-24
Socket Family Validation and Fallback Handling
The function invokes server.requestIP(c.req.raw) to query client connection properties. When operating over Unix domain sockets or processing closed requests, requestIP returns null, causing getConnInfo to return an empty remote object { remote: {} }.
Sources: src/adapter/bun/conninfo.ts:28-34
When valid socket information is returned, the adapter maps the properties to a standardized structure. The addressType field explicitly validates that the family string equals 'IPv6' or 'IPv4', assigning undefined for any unrecognized socket family.
Sources: src/adapter/bun/conninfo.ts:36-42
Static site generation support
Filesystem Modules and SSG Integration
The Bun adapter provides experimental static site generation bindings that bridge Hono's base SSG helper with Bun's high-performance file system APIs. The bunFileSystemModule defines a custom FileSystemModule interface implementation using Bun's native write method for writing build outputs.
Sources: src/adapter/bun/ssg.ts:1-19
/* eslint-disable @typescript-eslint/ban-ts-comment */
import { toSSG as baseToSSG } from '../../helper/ssg'
import type { FileSystemModule, ToSSGAdaptorInterface } from '../../helper/ssg'
// @ts-ignore
const { write } = Bun
/**
* @experimental
* `bunFileSystemModule` is an experimental feature.
* The API might be changed.
*/
export const bunFileSystemModule: FileSystemModule = {
writeFile: async (path, data) => {
await write(path, data)
},
mkdir: async () => {},
}
Sources: src/adapter/bun/ssg.ts:1-19
Warning
Both bunFileSystemModule and the toSSG adaptor function are marked as experimental. Their underlying APIs are subject to change in future releases.
Sources: src/adapter/bun/ssg.ts:8-12, src/adapter/bun/ssg.ts:20-24
SSG Adapter Interface Execution
The adapter exports a toSSG function matching the ToSSGAdaptorInterface signature. It delegates execution to the core baseToSSG helper, passing the application instance, the Bun-specific filesystem module, and user-provided generation options.
Sources: src/adapter/bun/ssg.ts:20-27
/**
* @experimental
* `toSSG` is an experimental feature.
* The API might be changed.
*/
export const toSSG: ToSSGAdaptorInterface = async (app, options) => {
return baseToSSG(app, bunFileSystemModule, options)
}Sources: src/adapter/bun/ssg.ts:20-27
Related
On This Page
OverviewEntry point and module exportsPublic Module SurfaceNative Bun server reference managementServer Retrieval via getBunServerStatic asset resolution via Bun.fileMiddleware Integration and Native HandlersConnection info extractionServer Request Metadata and Remote Address MappingSocket Family Validation and Fallback HandlingStatic site generation supportFilesystem Modules and SSG IntegrationSSG Adapter Interface ExecutionRelated