Bun

Get started by returning a Response object in fetch(request)

import {serve} from 'bun';

serve({
  fetch(req) {
    // something like this:
    return new Response('Hello world!');
  }
})
import {serve} from 'bun';

serve({
  fetch(req) {
    // something like this:
    return Response.json({hello: "World"});
  }
})
import {serve, file} from 'bun';

serve({
  fetch(req) {
    // something like this:
    return new Response(file("index.html"));
  }
})
import {serve} from 'bun';

serve({
  fetch(req, server) {
    return server.upgrade(req);
  },

  websocket: {
    message(ws, message) {
      ws.send(message);
    },
  },
})
import {serve} from 'bun';

serve({
  fetch(req) {
    // something like this:
    return Response.redirect("/redirected");
  }
})
import {serve} from 'bun';

serve({
  keyFile: process.env.SSL_KEY_FILE || "./key.pem",
  certFile: process.env.SSL_CERTIFICATE_FILE || "./cert.pem",

  fetch(req) {
    // something like this:
    return new Response("Hello HTTPS!");
  },
});

You are seeing this because fetch(req) did not return a Response object.

Built on web standards

Bun.serve() is built on web standards like Request and Response.

import {serve} from 'bun';

serve({
  async fetch(request) {
    // Read the request body as json
    const body = await request.json();
    
    const {headers} = request;
    const accept = headers.get("Accept");

    // Return an error if they're not asking for json
    if (accept !== "application/json") {
      return new Response(
        "Expected Accept: application/json header",
        {status: 400}
      );
    }

    // return a new Response with the body as json
    return Response.json(body);
  }
})

Why am I seeing this page?

You are seeing this page because the fetch() handler in Bun.serve() did not return a Response object.

I'm stuck. Can you help?

Please ask for help in Bun's Discord.