Meta tags:
description= Use Bun.serve to start a high-performance HTTP server in Bun;
Headings (most frequently used words):
server, request, and, sockets, http, default, system, port, documentation, index, on, this, page, basic, setup, html, imports, configuration, unix, domain, quic, idletimeout, export, syntax, hot, route, reloading, lifecycle, methods, per, controls, metrics, benchmarks, practical, example, rest, api, reference, get, started, core, runtime, file, module, networking, data, storage, concurrency, process, interop, tooling, utilities, standards, compatibility, contributing, changing, the, hostname, configuring, abstract, namespace, stop, ref, unref, reload, timeout, seconds, requestip, pendingrequests, pendingwebsockets, subscribercount, topic,
Text of the page (most frequently used words):
server (105), bun (70), the (55), response (41), port (34), req (34), serve (33), and (30), new (30), return (26), #request (25), fetch (24), string (21), http (21), for (20), void (17), const (17), routes (16), with (16), file (15), when (15), timeout (15), post (14), api (14), default (14), number (12), data (12), seconds (12), from (12), posts (12), this (11), all (11), boolean (11), websocket (11), unix (11), json (11), connection (10), sockets (10), stop (10), not (10), buffer (9), promise (9), requests (9), get (9), true (9), can (9), version (9), html (9), page (8), key (8), message (8), idletimeout (8), hostname (8), connections (8), set (8), error (8), hello (8), readonly (7), null (7), topic (7), reload (7), without (7), 404 (7), socket (7), options (6), tls (6), bunfile (6), serverwebsocket (6), called (6), alive (6), per (6), idle (6), url (6), process (6), only (6), running (6), client (6), address (6), content (6), export (6), status (6), console (6), text (6), import (6), type (6), runtime (6), domain (6), you (6), http3 (6), abstract (6), index (6), see (5), cert (5), closed (5), keep (5), bytes (5), undefined (5), returns (5), sent (5), upgrade (5), that (5), into (5), await (5), node (5), hot (5), your (5), namespace (5), environment (5), imports (5), build (5), blog (5), documentation (4), system (4), path (4), interface (4), received (4), code (4), whether (4), backpressure (4), development (4), pendingwebsockets (4), active (4), pendingrequests (4), flight (4), unref (4), ref (4), disable (4), requestip (4), subscribercount (4), clients (4), false (4), handlers (4), update (4), typescript (4), reference (4), created_at (4), title (4), async (4), 3000 (4), events (4), use (4), handler (4), quic (4), requires (4), pem (4), 4002 (4), log (4), copy (4), built (3), routing (3), router (3), array (3), ping (3), close (3), before (3), found (3), select (3), query (3), run (3), create (3), database (3), types (3), basic (3), rest (3), than (3), listen (3), chat (3), metrics (3), being (3), are (3), otherwise (3), streaming (3), body (3), pass (3), reloading (3), complete (3), route (3), udp (3), http1 (3), tcp (3), over (3), node_port (3), variable (3), bun_port (3), full (3), assets (3), module (3), lines (2), flags (2), passphrase (2), private (2), memory (2), certificate (2), pong (2), frame (2), messages (2), send (2), websocketcompressor (2), compress (2), maximum (2), mode (2), bound (2), including (2), thing (2), while (2), param (2), custom (2), count (2), subscribed (2), publish (2), headers (2), internal (2), updated (2), restarting (2), closeactiveconnections (2), resolves (2), immediately (2), accepting (2), params (2), where (2), list (2), sqlite (2), using (2), practical (2), example (2), 000 (2), second (2), linux (2), 8080 (2), res (2), benchmarks (2), users (2), chatusers (2), websockets (2), stream (2), will (2), long (2), lived (2), they (2), longer (2), inactivity (2), instead (2), entirely (2), controls (2), don (2), lifecycle (2), methods (2), containing (2), syntax (2), closes (2), streams (2), configure (2), listens (2), both (2), automatically (2), also (2), change (2), option (2), terminal (2), variables (2), which (2), configuring (2), randomly (2), available (2), defaults (2), object (2), changing (2), configuration (2), building (2), stack (2), applications (2), transpiler (2), css (2), bundler (2), myreactsinglepageapp (2), manifest (2), side (2), favicon (2), ico (2), world (2), redirect (2), start (2), setup (2), contributing (2), compatibility (2), apis (2), toml (2), cookies (2), install (2), search (2), hosted, mintlify, developer, platform, powered, youtube, discord, github, next, previous, raise, issue, suggest, edits, yes, was, helpful, 162, servername, name, sni, secureoptions, openssl, lowmemorymode, reduce, usage, dhparamsfile, parameters, authority, chain, tlsoptions, reason, open, opened, publishtoself, receives, its, own, published, sendpings, frames, decompress, permessagedeflate, enable, deflate, compression, drain, relieved, closeonbackpressurelimit, limit, hit, backpressurelimit, queued, applying, maxpayloadlength, size, websockethandler, instance, identifier, listening, protocol, allow, exit, socketaddress, serverwebsocketsendstatus, sharedarraybuffer, arraybuffer, arraybufferview, dropped, applied, headersinit, successful, failed, useful, testing, make, has, stopped, terminates, disposable, extends, definitions, 500, 201, toisostring, date, values, insert, randomuuid, crypto, omit, primary, table, exists, exec, here, backed, zero, dependencies, 160, handle, roughly, more, end, createserver, require, following, servers, respond, each, incoming, subscribe, subscribers, monitor, activity, counters, unknown, information, event, arrive, sporadically, killed, yield, function, like, raising, global, every, done, take, aborted, give, override, individual, restore, behavior, control, keeps, allows, terminate, force, gracefully, waits, deploy, downtime, restarts, sees, passes, parameter, add, attaches, replace, satisfies, passing, them, timer, applies, streamed, goes, quiet, mid, field, value, disables, 255, after, still, but, hasn, written, any, yet, browsers, reset, supported, listener, enabled, same, responses, include, header, advertising, endpoint, capable, alt, svc, together, support, may, future, releases, experimental, unlike, filesystem, removed, last, supports, prefix, byte, tmp, sock, cli, flag, several, uses, localhost, read, chosen, property, selected, random, mydomain, com, guide, fullstack, dev, just, javascript, parser, frontends, react, tailwind, statement, pre, bundled, serves, bundling, target, production, bundles, demand, enables, replacement, hmr, frontend, browser, updates, files, directly, work, two, modes, required, optional, fallback, unmatched, lazily, loading, wildcard, aren, matched, created, method, user, dynamic, static, high, performance, license, bindgen, windows, benchmarking, roadmap, web, globals, standards, utils, color, semver, glob, hashing, image, htmlrewriter, jsonl, json5, markdown, yaml, secrets, csrf, protection, utilities, compiler, ffi, interop, tooling, cron, webview, spawn, shell, workers, concurrency, redis, sql, archive, binary, storage, dns, networking, handling, plugins, auto, jsx, resolution, bunfig, repl, debugging, watch, core, init, quickstart, installation, welcome, started, feedback, guides, test, runner, package, manager, navigation, home, skip, main, discover, pages, exploring, further, docs, llms, txt,
Text of the page (random words):
ndex at docs llms txt use this file to discover all available pages before exploring further skip to main content bun home page search k install bun search navigation http server server runtime package manager bundler test runner guides reference blog feedback get started welcome to bun installation quickstart typescript typescript 6 and 7 bun init bun create core runtime bun runtime watch mode debugging repl bunfig toml file module system file types module resolution jsx auto install plugins file system router http server server routing cookies tls error handling metrics networking fetch websockets tcp udp dns data storage cookies file i o streams binary data archive sql sqlite s3 redis concurrency workers process system environment variables shell spawn webview cron interop tooling node api ffi c compiler transpiler utilities csrf protection secrets console toml yaml markdown json5 jsonl htmlrewriter image hashing glob semver color utils standards compatibility globals bun apis web apis node js compatibility contributing roadmap benchmarking contributing building windows bindgen license on this page basic setup html imports configuration changing the port and hostname configuring a default port unix domain sockets abstract namespace sockets http 3 quic idletimeout export default syntax hot route reloading server lifecycle methods server stop server ref and server unref server reload per request controls server timeout request seconds server requestip request server metrics server pendingrequests and server pendingwebsockets server subscribercount topic benchmarks practical example rest api reference http server server copy page copy page use bun serve to start a high performance http server in bun copy page copy page basic setup index ts const server bun serve routes requires bun v1 2 3 routes static routes api status new response ok dynamic routes users id req return new response hello user req params id per http method handlers api posts get new response list posts post async req const body await req json return response json created true body wildcard route for all routes that start with api and aren t otherwise matched api response json message not found status 404 redirect from blog hello to blog hello world blog hello response redirect blog hello world serve a file by lazily loading it into memory favicon ico bun file favicon ico optional fallback for unmatched routes required if bun s version 1 2 3 fetch req return new response not found status 404 console log server running at server url html imports import html files directly into your server code to build full stack applications with both server side and client side code html imports work in two modes development bun hot bun bundles assets on demand at runtime and enables hot module replacement hmr when you change your frontend code the browser updates without a full page reload production bun build when you build with bun build target bun the import index from index html statement resolves to a pre built manifest object containing all bundled client assets bun serve serves the assets from this manifest with no bundling at runtime import myreactsinglepageapp from index html bun serve routes myreactsinglepageapp html imports don t just serve html they run bun s bundler javascript transpiler and css parser so you can build frontends with react typescript and tailwind css for a complete guide to building full stack applications with html imports see fullstack dev server configuration changing the port and hostname to configure which port and hostname the server listens on set port and hostname in the options object bun serve port 8080 defaults to bun_port port node_port otherwise 3000 hostname mydomain com defaults to 0 0 0 0 fetch req return new response 404 to randomly select an available port set port to 0 const server bun serve port 0 random port fetch req return new response 404 server port is the randomly selected port console log server port read the chosen port from the server s port or url property console log server port 3000 console log server url http localhost 3000 configuring a default port several flags and environment variables set the default port which bun uses when the port option is not set port cli flag bun port 4002 server ts bun_port environment variable bun_port 4002 bun server ts port environment variable terminal port 4002 bun server ts node_port environment variable terminal node_port 4002 bun server ts unix domain sockets to listen on a unix domain socket pass the unix option with the path to the socket bun serve unix tmp my socket sock path to socket fetch req return new response 404 abstract namespace sockets on linux bun also supports abstract namespace sockets prefix the unix path with a null byte bun serve unix 0 my abstract socket abstract namespace socket fetch req return new response 404 unlike unix domain sockets abstract namespace sockets are not bound to the filesystem and are automatically removed when the last reference to the socket is closed http 3 quic http 3 support in bun serve is experimental and may change in future releases bun serve can also listen for http 3 over quic set http3 true together with tls http 3 requires tls bun serve tls key bun file key pem cert bun file cert pem http3 true fetch req return new response hello over http 3 when http3 is enabled the server listens on the same port over both tcp http 1 1 and udp http 3 http 1 1 responses include an alt svc header advertising the http 3 endpoint so capable clients can upgrade automatically to serve http 3 only no tcp listener at all set http1 false bun serve tls key bun file key pem cert bun file cert pem http3 true http1 false fetch req return new response http 3 only http3 is not supported with unix domain sockets quic requires a udp port http1 false requires http3 true idletimeout by default bun serve closes connections after 10 seconds of inactivity a connection is idle when no data is being sent or received including in flight requests where your handler is still running but hasn t written any bytes to the response yet browsers and fetch clients see this as a connection reset to configure this set the idletimeout field in seconds the maximum value is 255 and 0 disables the timeout entirely bun serve 30 seconds default is 10 idletimeout 30 fetch req return new response bun streaming server sent events the idle timer applies while a response is being streamed if your stream goes quiet for longer than idletimeout bun closes the connection mid response for long lived streams disable the timeout for that request with server timeout req 0 export default syntax instead of passing the server options into bun serve you can export default them server ts import type serve from bun export default fetch req return new response bun satisfies serve options undefined the type parameter undefined is the websocket data type if you add a websocket handler that attaches custom data with server upgrade req data replace undefined with your data type you can run this file as is when bun sees a file with a default export containing a fetch handler it passes it into bun serve hot route reloading update routes without server restarts using server reload const server bun serve routes api version response json version 1 0 0 deploy new routes without downtime server reload routes api version response json version 2 0 0 server lifecycle methods server stop to stop the server from accepting new connections const server bun serve fetch req return new response hello gracefully stop the server waits for in flight requests await server stop force stop and close all active connections await server stop true by default stop allows in flight requests and websocket connections to complete pass true to immediately terminate all connections server ref and server unref control whether the server keeps the bun process alive don t keep process alive if server is the only thing running server unref restore default behavior keep process alive server ref server reload update the server s handlers without restarting const server bun serve routes api version response json version v1 fetch req return new response v1 update to new handler server reload routes api version response json version v2 fetch req return new response v2 use this for development and hot reloading only fetch error routes and websocket can be updated per request controls server timeout request seconds override the idle timeout for an individual request pass 0 to disable the timeout entirely for that request const server bun serve async fetch req server give this request up to 60 seconds of inactivity instead of the default 10 server timeout req 60 if they take longer than 60 seconds to send the body the request will be aborted await req text return new response done use server timeout req 0 to keep a long lived streaming response like server sent events alive without raising the global idletimeout for every request bun serve routes events req server disable the idle timeout for this streaming response otherwise the connection will be closed if no bytes are sent for 10 seconds the default idletimeout server timeout req 0 return new response async function yield data hello n n events can arrive sporadically without the connection being killed headers content type text event stream server requestip request get client ip and port information const server bun serve fetch req server const address server requestip req if address return new response client ip address address port address port return new response unknown client returns null for closed requests or unix domain sockets server metrics server pendingrequests and server pendingwebsockets monitor server activity with built in counters const server bun serve fetch req server return new response active requests server pendingrequests n active websockets server pendingwebsockets server subscribercount topic get count of subscribers for a websocket topic const server bun serve fetch req server const chatusers server subscribercount chat return new response chatusers users in chat websocket message ws ws subscribe chat benchmarks the following bun and node js servers respond bun to each incoming request bun bun serve fetch req request return new response bun port 3000 require http createserver req res res end bun listen 8080 the bun serve server can handle roughly 2 5x more requests per second than node js on linux runtime requests per second node 16 64 000 bun 160 000 practical example rest api here s a basic database backed rest api using bun s router with zero dependencies server ts types ts import type post from types ts import database from bun sqlite const db new database posts db db exec create table if not exists posts id text primary key title text not null content text not null created_at text not null bun serve routes list posts api posts get const posts db query select from posts all return response json posts create post post async req const post omit post id created_at await req json const id crypto randomuuid db query insert into posts id title content created_at values run id post title post content new date toisostring return response json id post status 201 get post by id api posts id req const post db query select from posts where id get req params id if post return new response not found status 404 return response json post error error console error error return new response internal server error status 500 see all 53 lines export interface post id string title string content string created_at string reference see typescript definitions interface server extends disposable stop the server from accepting new connections param closeactiveconnections if true immediately terminates all connections returns promise that resolves when the server has stopped stop closeactiveconnections boolean promise void update handlers without restarting the server only fetch and error handlers can be updated reload options serve void make a request to the running server useful for testing or internal routing fetch request request string response promise response upgrade an http request to a websocket connection returns true if upgrade successful false if failed upgrade t undefined request request options headers bun headersinit data t boolean publish a message to all websocket clients subscribed to a topic returns bytes sent 0 if dropped 1 if backpressure applied publish topic string data string arraybufferview arraybuffer sharedarraybuffer compress boolean serverwebsocketsendstatus get count of websocket clients subscribed to a topic subscribercount topic string number get client ip address and port returns null for closed requests or unix sockets requestip request request socketaddress null set custom idle timeout for a request param seconds timeout in seconds 0 to disable timeout request request seconds number void keep process alive while server is running ref void allow process to exit if server is only thing running unref void number of in flight http requests readonly pendingrequests number number of active websocket connections readonly pendingwebsockets number server url including protocol hostname and port readonly url url port server is listening on readonly port number hostname server is bound to readonly hostname string whether server is in development mode readonly development boolean server instance identifier readonly id string interface websockethandler t undefined maximum websocket message size in bytes maxpayloadlength number bytes of queued messages before applying backpressure backpressurelimit number whether to close connection when backpressure limit hit closeonbackpressurelimit boolean called when backpressure is relieved drain ws serverwebsocket t void promise void seconds before idle timeout idletimeout number enable per message deflate compression permessagedeflate boolean compress websocketcompressor boolean decompress websocketcompressor boolean send ping frames to keep connection alive sendpings boolean whether server receives its own published messages publishtoself boolean called when connection opened open ws serverwebsocket t void promise void called when message received message ws serverwebsocket t message string buffer void promise void called when connection closed close ws serverwebsocket t code number reason string void promise void called when ping frame received ping ws serverwebsocket t data buffer void promise void called when pong frame received pong ws serverwebsocket t data buffer void promise void interface tlsoptions certificate authority chain ca string buffer bunfile array string buffer bunfile server certificate cert string buffer bunfile array string buffer bunfile path to dh parameters file dhparamsfile string private key key string buffer bunfile array string buffer bunfile reduce tls memory usage lowmemorymode boolean private key passphrase passphrase string openssl options flags secureoptions number server name for s...
|