HTTP and SQLite

Start an HTTP server

Create a small HTTP server with Bun.serve and return a Web Standard Response from its fetch handler.

8 minute lesson

~~~

Bun.serve() starts an HTTP server. Its fetch function receives a Web Standard Request and returns a Response.

Replace index.ts with:

const server = Bun.serve({
  port: Number(Bun.env.PORT ?? 3000),
  fetch() {
    return new Response('Bun Notes is running')
  },
})

console.log(`Listening on ${server.url}`)

Start the server:

bun --watch index.ts

Open http://localhost:3000 in your browser. You can also make the request with curl:

curl http://localhost:3000

The response is:

Bun Notes is running

Read the request

The request contains the method, URL, headers, and body sent by the client.

Return a small JSON description of each request:

const server = Bun.serve({
  fetch(request) {
    const url = new URL(request.url)

    return Response.json({
      method: request.method,
      path: url.pathname,
    })
  },
})

console.log(`Listening on ${server.url}`)

Request, Response, and URL are the same core APIs used by browsers and other modern runtimes. This makes the HTTP boundary familiar and easier to test.

Keep the port configurable. Deployment platforms normally provide it through a PORT environment variable.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →