Bun
@navios/adapter-bun runs a Navios application on Bun.serve. The adapter registers the application's routes with Bun's router, turns each Request into the input of a compiled route and builds a Response from the result. Guards, validation and error mapping happen in @navios/server and behave the same as on every other adapter.
Bun runs the standard decorators Navios uses as they are, so an application needs no extra build step or compiler option.
Install and use
The adapter has no runtime dependencies of its own.
app.listen({ port?, hostname? }) defaults to port 3000 on localhost and resolves to the server's base URL. Pass port: 0 for an ephemeral port. app.getServer() returns the Bun Server; Bun creates it when it starts listening, so the call throws before listen().
In tests, app.inject() builds a Request and runs it through the same route handlers and CORS handling without opening a socket. It chooses the route as Bun.serve does. See Testing.
Options
Both options of defineBunEnvironment(options) are optional.
With serve.unix the server listens on that socket, and app.listen({}) takes no port or hostname.
An error that Bun raises while it sends a response, for example for a Bun.file() that is not there, is logged and answered with a 500 problem response. serve.error replaces that.
The Register declaration
Write this once in the application, usually next to NaviosFactory.create. It types ctx.raw, app.getServer() and the options of app.listen() for Bun. Request context explains the mechanism and what happens without the declaration.
What ctx.raw contains
ctx.raw.server is null for requests handled through app.inject() before app.listen() has been called.
Bun has no request id, so ctx.id is generated by @navios/server on first read. ctx.signal is the request's own signal, and ctx.ip the address of the connection, from server.requestIP().
Code that uses ctx.raw runs on this adapter only. Prefer the adapter-neutral members of the context (ctx.ip, ctx.headers, ctx.cookies, ctx.reply.header(), ctx.signal) where they cover the need.
Taking over the response
There is no native reply object on Bun, so a handler cannot write the response itself, except by upgrading its request to a WebSocket. It returns a value, and for streaming it returns a ReadableStream or an async iterable from an endpoint declared with response: 'stream'. See Streams and server-sent events.
WebSockets
Pass the handlers of the sockets as serve.websocket, as for Bun.serve, and upgrade the request in a handler, behind its guards:
BunEnvironment<SocketData>in theRegisterdeclaration typesdataandapp.getServer().- What the handler of an upgraded request returns is ignored, whatever the endpoint declares.
ctx.responseStatusis 101. - The request is released when it has been upgraded. The handlers of the socket run outside any request.
- Closing the application closes the sockets as soon as no request is in flight.
Idle connections
Bun closes a connection on which nothing has been sent for serve.idleTimeout, 10 seconds by default, also while a handler is running. Raise it for handlers that need longer, and for streams that are quiet for longer.
It does not apply to an event stream (sseStream(), or another stream with the content type text/event-stream): the adapter turns it off for the request, with server.timeout(request, 0), until the stream has ended.
CORS
CORS is implemented by the adapter and applied once per response, including error and not-found responses. A preflight request (OPTIONS with Origin and Access-Control-Request-Method) is answered with 204, also on a path with an OPTIONS route.
A function for origin receives (origin, callback). It answers with any of the other values: by calling callback(null, value), or by returning a promise of the value. One that takes only origin may return the value itself; from a function with a callback, a value that is not a promise decides nothing. It is called before the handler, for requests that have an origin. When it fails, or calls back with an error, the error is logged and the request is answered with a 500 problem response.
A request from an origin that is not allowed is still handled; it gets no CORS headers, and the browser blocks the response. A preflight request from such an origin is answered like any other OPTIONS request: with 405 on a path that is served for other methods, and with the not-found response elsewhere.
origin: '*' together with credentials: true is not allowed by the CORS specification, so the adapter throws when the application is initialised with that combination, including when origin is left out. Set origin to the allowed origin or origins, or use origin: true to reflect the request's origin.
Multipart
Multipart needs no option. An endpoint declared with body: 'multipart' receives text fields as strings and files as File objects, validated by the endpoint's requestSchema. File uploads covers the handler side.
The body is parsed with request.formData(), which reads the whole body into memory. Limit the size with serve.maxRequestBodySize; the limit applies to the whole multipart body, not to each file.
Bun takes the type of a File from the extension of its name, not from the content type of the part. The name is never a path: ../../etc/passwd arrives as passwd.
Request bodies
- The body is read only when the pipeline asks for it, which is after guards have passed, and then decoded by its content type.
- A request with two
Content-Typeheaders is a 415, because Bun joins them. - A body can be read once. A handler that reads
ctx.raw.requestitself belongs to an endpoint without arequestSchema; next to one, usectx.rawBody().
Body size limit
serve.maxRequestBodySize (128 MiB by default, as in Bun) limits the size of a request body, whatever its content type. A larger body is answered with a 413 problem response.
The adapter enforces the limit itself and starts Bun.serve without one, because Bun answers an oversize body with an empty 413 that no handler or error hook can replace. When the limit applies depends on whether the request declares its length:
Routing
Routes are matched by Bun's router, with these rules of its own:
- Fixed text is compared as it is sent. A character that needs no percent-encoding is not recognised when it is encoded:
/%75sersis not/users, and/users/m%65reaches/users/$idrather than/users/me. - A URL parameter that is not valid percent-encoding is a 400, as on Fastify.
- The methods are
GET,POST,PUT,DELETE,PATCH,HEADandOPTIONS. An endpoint with another one makesinit()throw. - A request that Bun cannot read is answered with an empty 400 or 431, or its connection is closed.
Shutdown
app.close() stops accepting connections and waits for requests in flight, streams included, for at most the application's shutdownTimeout (10 seconds by default). Then it closes the connections that are left, and the application continues with its shutdown hooks. A connection on which no request was sent is not waited for. Application setup describes the whole shutdown sequence.
Requirements
- Bun 1.4.5 or newer
@navios/serverof the same version (peer dependency), with@navios/builder