The type of options that can be passed to serve, with support for routes
and a safer requirement for fetch
Symbol
ServeFunctionOptions
type ServeFunctionOptions<T, R extends { [K in keyof R]: RouterTypes.RouteValue<Extract<K, string>> }> = DistributedOmit<Exclude<Serve<T>, WebSocketServeOptions<T>>, 'fetch'> & { fetch: (this: Server, request: Request, server: Server) => Response | Promise<Response>; routes: R } | DistributedOmit<Exclude<Serve<T>, WebSocketServeOptions<T>>, 'routes'> & { fetch: (this: Server, request: Request, server: Server) => Response | Promise<Response>; routes: never } | Omit<WebSocketServeOptions<T>, 'fetch'> & { fetch: (this: Server, request: Request, server: Server) => Response | Promise<Response | void | undefined> | void | undefined; routes: { [K in keyof R]: RouterTypes.RouteValueWithWebSocketUpgrade<Extract<K, string>> } } | Omit<WebSocketServeOptions<T>, 'fetch'> & { fetch: (this: Server, request: Request, server: Server) => Response | Promise<Response | void | undefined> | void | undefined; routes: never }
Referenced types
type DistributedOmit<T, K extends PropertyKey> = T extends T ? Omit<T, K> : never
type Serve<WebSocketDataType = undefined> = ServeOptions | TLSServeOptions | UnixServeOptions | UnixTLSServeOptions | WebSocketServeOptions<WebSocketDataType> | TLSWebSocketServeOptions<WebSocketDataType> | UnixWebSocketServeOptions<WebSocketDataType> | UnixTLSWebSocketServeOptions<WebSocketDataType>
The type of options that can be passed to serve
interface WebSocketServeOptions<WebSocketDataType = undefined>
- id?: null | string
Uniquely identify a server instance with an ID
When bun is started with the
--hot
flagThis string will be used to hot reload the server without interrupting pending requests or websockets. If not provided, a value will be generated. To disable hot reloading, set this value to
null
.When bun is not started with the
--hot
flagThis string will currently do nothing. But in the future it could be useful for logs or metrics.
- websocket: WebSocketHandler<WebSocketDataType>
Enable websockets with Bun.serve
For simpler type safety, see Bun.websocket
Bun.serve({ websocket: { open: (ws) => { console.log("Client connected"); }, message: (ws, message) => { console.log("Client sent message", message); }, close: (ws) => { console.log("Client disconnected"); }, }, fetch(req, server) { const url = new URL(req.url); if (url.pathname === "/chat") { const upgraded = server.upgrade(req); if (!upgraded) { return new Response("Upgrade failed", { status: 400 }); } } return new Response("Hello World"); }, });
Upgrade a Request to a ServerWebSocket via Server.upgrade
Pass
data
in @{link Server.upgrade} to attach data to the ServerWebSocket.data property