fetch

Bun

Symbol

ServeOptions.fetch

fetch(this: Server, request: Request, server: Server): Response | Promise<Response>

Handle HTTP requests

Respond to Request objects with a Response object.

Referenced types

interface Server

HTTP & HTTPS Server

To start the server, see serve

For performance, Bun pre-allocates most of the data for 2048 concurrent requests. That means starting a new server allocates about 500 KB of memory. Try to avoid starting and stopping the server often (unless it's a new instance of bun).

Powered by a fork of uWebSockets. Thank you @alexhultman.

  • readonly development: boolean

    Is the server running in development mode?

    In development mode, Bun.serve() returns rendered error messages with stack traces instead of a generic 500 error. This makes debugging easier, but development mode shouldn't be used in production or you will risk leaking sensitive information.

  • readonly hostname: undefined | string

    The hostname the server is listening on. Does not include the port.

    This will be undefined when the server is listening on a unix socket.

    "localhost"
    
  • readonly id: string

    An identifier of the server instance

    When bun is started with the --hot flag, this ID is used to hot reload the server without interrupting pending requests or websockets.

    When bun is not started with the --hot flag, this ID is currently unused.

  • readonly pendingRequests: number

    How many requests are in-flight right now?

  • readonly pendingWebSockets: number

    How many ServerWebSockets are in-flight right now?

  • readonly port: undefined | number

    The port the server is listening on.

    This will be undefined when the server is listening on a unix socket.

    3000
    
  • readonly url: URL
  • fetch(request: string | Request): Response | Promise<Response>

    Mock the fetch handler for a running server.

    This feature is not fully implemented yet. It doesn't normalize URLs consistently in all cases and it doesn't yet call the error handler consistently. This needs to be fixed

  • publish(topic: string, data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>, compress?: boolean): number

    Send a message to all connected ServerWebSocket subscribed to a topic

    @param topic

    The topic to publish to

    @param data

    The data to send

    @param compress

    Should the data be compressed? Ignored if the client does not support compression.

    @returns

    0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.

    server.publish("chat", "Hello World");
    
  • ref(): void

    Undo a call to Server.unref

    If the Server has already been stopped, this does nothing.

    If Server.ref is called multiple times, this does nothing. Think of it as a boolean toggle.

  • reload<T, R extends { [K in string | number | symbol]: RouteValue<K & string> }>(options: ServeFunctionOptions<T, R> & { static: R }): Server

    Update the fetch and error handlers without restarting the server.

    This is useful if you want to change the behavior of your server without restarting it or for hot reloading.

    // create the server
    const server = Bun.serve({
     fetch(request) {
       return new Response("Hello World v1")
     }
    });
    
    // Update the server to return a different response
    server.reload({
      fetch(request) {
        return new Response("Hello World v2")
      }
    });
    

    Passing other options such as port or hostname won't do anything.

  • requestIP(request: Request): null | SocketAddress

    Returns the client IP address and port of the given Request. If the request was closed or is a unix socket, returns null.

    export default {
     async fetch(request, server) {
       return new Response(server.requestIP(request));
     }
    }
    
  • stop(closeActiveConnections?: boolean): Promise<void>

    Stop listening to prevent new connections from being accepted.

    By default, it does not cancel in-flight requests or websockets. That means it may take some time before all network activity stops.

    @param closeActiveConnections

    Immediately terminate in-flight requests, websockets, and stop accepting new connections.

  • subscriberCount(topic: string): number

    A count of connections subscribed to a given topic

    This operation will loop through each topic internally to get the count.

    @param topic

    the websocket topic to check how many subscribers are connected to

    @returns

    the number of subscribers

  • timeout(request: Request, seconds: number): void

    Reset the idleTimeout of the given Request to the number in seconds. 0 means no timeout.

    export default {
     async fetch(request, server) {
       server.timeout(request, 60);
       await Bun.sleep(30000);
       return new Response("30 seconds have passed");
     }
    }
    
  • unref(): void

    Don't keep the process alive if this server is the only thing left. Active connections may continue to keep the process alive.

    By default, the server is ref'd.

    To prevent new connections from being accepted, use Server.stop

  • upgrade<T = undefined>(request: Request, options?: { data: T; headers: HeadersInit }): boolean

    Upgrade a Request to a ServerWebSocket

    @param request

    The Request to upgrade

    @param options

    Pass headers or attach data to the ServerWebSocket

    @returns

    true if the upgrade was successful and false if it failed

    import { serve } from "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");
       },
     });
    

    What you pass to data is available on the ServerWebSocket.data property

class Request

This Fetch API interface represents a resource request.

MDN Reference

  • readonly body: null | ReadableStream<Uint8Array<ArrayBufferLike>>
  • readonly bodyUsed: boolean
  • readonly cache: RequestCache

    Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching.

    MDN Reference

  • readonly credentials: RequestCredentials

    Returns the credentials mode associated with request, which is a string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL.

    MDN Reference

  • readonly destination: RequestDestination

    Returns the kind of resource requested by request, e.g., "document" or "script".

    MDN Reference

  • readonly headers: Headers

    Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header.

    MDN Reference

  • readonly integrity: string

    Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI]

    MDN Reference

  • readonly keepalive: boolean

    Returns a boolean indicating whether or not request can outlive the global in which it was created.

    MDN Reference

  • readonly method: string

    Returns request's HTTP method, which is "GET" by default.

    MDN Reference

  • readonly mode: RequestMode

    Returns the mode associated with request, which is a string indicating whether the request will use CORS, or will be restricted to same-origin URLs.

    MDN Reference

  • readonly redirect: RequestRedirect

    Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default.

    MDN Reference

  • readonly referrer: string

    Returns the referrer of request. Its value can be a same-origin URL if explicitly set in init, the empty string to indicate no referrer, and "about:client" when defaulting to the global's default. This is used during fetching to determine the value of the Referer header of the request being made.

    MDN Reference

  • readonly referrerPolicy: ReferrerPolicy

    Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer.

    MDN Reference

  • readonly signal: AbortSignal

    Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler.

    MDN Reference

  • readonly url: string
  • bytes(): Promise<Uint8Array<ArrayBufferLike>>
  • json(): Promise<any>
  • text(): Promise<string>

class Response

This Fetch API interface represents the response to a request.

MDN Reference