> ## Documentation Index
> Fetch the complete documentation index at: https://fairyfly.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# http API

> http.serve reference — signatures, options, handler contract, and helpers.

The `http` module starts servers. It has one function, `http.serve`, plus the response helpers you return from your handler.

## Permissions

`http.serve` listens on the network, so it always needs `--allow-net` on the
bind address:

```sh theme={null}
ff server.js --allow-net=0.0.0.0:3000
```

* The server binds to `0.0.0.0`; there is no host option. The check is always
  `0.0.0.0:<port>`, even when clients connect over loopback. Granting
  `127.0.0.1:3000` or `localhost:3000` will **not** let the server start.
* A scope without a port matches every port: `--allow-net=0.0.0.0` is enough
  for any listener port.
* The same grant covers HTTP, WebSocket upgrades, and TLS on that port.
* A denied listener throws synchronously from `http.serve`:

```js theme={null}
try {
  http.serve({ port: 3000 }, handler);
} catch (e) {
  console.error(e.name, e.code); // PermissionDenied PERMISSION_DENIED
  console.error(e.message);      // http.serve requires --allow-net for '0.0.0.0:3000'
}
```

### TLS files need `read`

`tls.cert` and `tls.key` are either inline PEM (the string starts with
`-----BEGIN `) or a file path. Inline PEM needs no file permission; a path
needs `--allow-read` on that file:

```sh theme={null}
ff server.js \
  --allow-net=0.0.0.0:3000 \
  --allow-read=cert.pem,key.pem
```

A denied TLS path throws `PermissionDenied` with messages like
`http.serve tls.cert requires --allow-read for 'cert.pem'` (and the same for
`tls.key`) before the listener starts. Path scopes follow the normal rules:
resolved against the launch cwd, symlink-checked, and not moved by
`process.chdir()`.

The `FF_CERT` / `FF_KEY` env vars used by `ff start` are read by the CLI and do
**not** need `--allow-read`. Only paths passed to `http.serve({ tls })` are
runtime reads.

Full model: [Permissions](https://fairyfly.dev/concepts/permissions.md).

## Quick look

```js theme={null}
// server.js
http.serve({ port: 3000 }, (url, method, body) => {
  return new Response("hello");
});
```

```sh theme={null}
ff server.js --allow-net=0.0.0.0:3000
curl http://127.0.0.1:3000/
# hello
```

## `http.serve(signatures)`

Two call shapes are accepted, and both return a server handle (`{ port, close }`):

```js theme={null}
const srv = http.serve(3000, handler);           // port shorthand
const srv = http.serve({ port: 4242 }, handler); // options object
```

| Signature | Port used | Returns |
| - | - | - |
| `http.serve(port, handler)` | `port` (`0` picks an ephemeral OS port) | `{ port: number, close(callback?): Promise<void> }` |
| `http.serve(options, handler)` | `options.port`, or `3000` when omitted | `{ port: number, close(callback?): Promise<void> }` |

The server binds to `0.0.0.0`. There is no host option. When `port: 0` is
passed, `srv.port` contains the actual bound port assigned by the OS.

> [!NOTE]
>
> The one-argument form `http.serve(handler)` is **not** supported by
> the current runtime — it throws `TypeError: http.serve requires (options, handler)`.
> Use `http.serve(3000, handler)` or `http.serve({}, handler)` for the default port.

## Options reference

```js theme={null}
const server = http.serve(
  {
    port: 3000,                       // default 3000 (0 for ephemeral port)
    reusePort: false,                 // optional — enables SO_REUSEPORT
    signal: ac.signal,                // optional — AbortSignal that calls server.close()
    tls: { cert: "...", key: "..." }, // optional — enables HTTPS/WSS on the same port
    websocket: {                      // optional — enables WebSocket upgrades
      open: (socket) => {},
      message: (socket, data) => {},
      close: (socket) => {},
    },
  },
  handler,
);
```

| Option | Type | Default | Description |
| - | - | - | - |
| `port` | `number` | `3000` | Listen port (`0` lets the OS pick an available port) |
| `reusePort` | `boolean` | `false` | Enables `SO_REUSEPORT` on the listening socket |
| `signal` | `AbortSignal` | none | Aborting the signal triggers `server.close()` |
| `tls` | `{ cert, key }` | none | PEM certificate + private key. Each value is either inline PEM (starts with `-----BEGIN `) or a file path. Cert max 512KB, key max 256KB. Enables HTTPS and WSS alongside plain HTTP/WS |
| `websocket.open` | `(socket) => void` | none | Fires when a client completes the upgrade |
| `websocket.message` | `(socket, data) => void` | none | Fires per frame; `data` is a string (text) or `Uint8Array` (binary) |
| `websocket.close` | `(socket) => void` | none | Fires when a client disconnects |

## Graceful shutdown: `server.close()` and signals

`server.close(callback?)` stops accepting new connections and drains existing
ones cleanly:

* Closes the listening socket immediately so new connections are refused.
* Closes idle HTTP/1.1 keep-alive sockets and active WebSocket connections.
* Marks in-flight HTTP/1.1 requests with `Connection: close` so each socket
  closes as soon as its response finishes flushing.
* Sends HTTP/2 `GOAWAY` on active H2 sessions and closes them once active
  streams complete.
* Resolves the returned `Promise<void>` (and invokes optional `callback`) once
  all 512 connection slots are free, allowing the event loop to exit naturally.

```js theme={null}
const server = http.serve({ port: 3000 }, handler);

process.once("SIGTERM", async () => {
  await server.close();
  console.log("drained cleanly");
});
```

If you do **not** register your own `SIGINT` or `SIGTERM` listener via
`process.on` / `process.once`, `http.serve` automatically traps `SIGINT` and
`SIGTERM` and calls `server.close()` for you.

When the `websocket` block is present, any request carrying
`Connection: Upgrade`, `Upgrade: websocket`, and `Sec-WebSocket-Key` is
upgraded **before your handler runs** — the handler never sees that
request, and no `{ status: 101 }` branch is needed (a handler that would
return 404 still gets the `101`). The handler serves plain HTTP only:

```js theme={null}
// server.js
http.serve(
  {
    port: 3000,
    websocket: {
      open: (socket) => socket.send("welcome"),
      message: (socket, data) => socket.send(data),
      close: (socket) => console.log("bye"),
    },
  },
  (url, method, body) => new Response("http here, ws upgrades on this port"),
);
```

WebSocket upgrades share the listener's net grant:
`--allow-net=0.0.0.0:3000`.

Server sockets expose `send` / `sendBinary` only — track peers by object reference in a `Set` (see the WebSocket guide).

## Handler reference

The handler is called as `(url, method, body, headers)`:

| Argument | Type | Example |
| - | - | - |
| `url` | `string` | `"/greet?name=ada"` (path + query) |
| `method` | `string` | `"GET"`, `"POST"` — exactly as the client sent it (`curl -X post` yields `"post"`); normalize case before comparing |
| `body` | `string` | Request text, `""` when none |
| `headers` | `Headers` | Web-standard `Headers` instance populated with incoming request headers (HTTP/1.1 and HTTP/2) |

Return one of:

| Return value | Effect |
| - | - |
| `Response` | Status, headers, and body sent as-is |
| `{ status, body }` (`string` or `ArrayBuffer` body) | Sent with that status code |
| `Promise` of either shape | Connection parks until it settles |
| Anything else (incl. bare strings) | Empty `200` response |

Async handlers work — the 30s watchdog still applies:

```js theme={null}
http.serve({ port: 3000 }, async (url, method, body) => {
  const res = await fetch("https://example.com/");
  return new Response(await res.text());
});
```

An async handler that calls out needs grants for **both** sides:

```sh theme={null}
ff server.js \
  --allow-net=0.0.0.0:3000,example.com:443
```

The listener is granted by `0.0.0.0:3000`; the outbound `fetch` is granted by
`example.com:443`. One repeatable flag can carry both scopes.

## Response helpers

Build responses with the global `Response` class:

```js theme={null}
return new Response("text");                          // 200 text/plain by default
return new Response("missing", { status: 404 });      // custom status
return Response.json({ hello: "world" });             // JSON + content-type, optional init
return Response.json({ id: 1 }, { status: 201 });     // with status
return Response.redirect("/new-path");                // 302 status only — no Location header
return Response.redirect("/moved", 301);              // 301 status only — no Location header
```

| Helper | Signature | Notes |
| - | - | - |
| `new Response(body, init?)` | `body`: `string \| ArrayBuffer \| Uint8Array \| null`; `init`: `{ status?, headers? }` | Default `content-type` is `text/plain` when the body has none |
| `Response.json(data, init?)` | any JSON-serializable `data` | Sets `content-type: application/json` |
| `Response.redirect(url, status?)` | redirect target + status (default 302) | Known issue: sets the status but **no `Location` header**, so no client follows it — send `Location` yourself (see [fetch Gotchas](https://fairyfly.dev/api/fetch.md#gotchas)) |
| `Response.error()` | — | Status `0`, type `"error"` (fetch-network-error shape) |

Read bodies back with `text()` / `json()` / `arrayBuffer()` / `bytes()` / `blob()` / `formData()` — all work on `Request` and `Response`. Bodies can be re-read freely (`bodyUsed` stays `false`; `bytes()` returns `ArrayBuffer`).

Headers are case-insensitive and lowercased internally:

```js theme={null}
const h = new Headers({ "Content-Type": "text/html" });
h.get("content-type"); // "text/html"
h.set("x-id", "1");
h.append("x-id", "2");
h.getAll("x-id");      // ["1", "2"]
h.has("x-id");         // true
h.delete("x-id");
h.entries(); h.keys(); h.values();
h.forEach((value, key) => console.log(key, value));
```

## Full example

```js theme={null}
// server.js
http.serve({ port: 3000 }, (url, method, body) => {
  const path = new URL(url, "http://localhost").pathname;

  if (path === "/json") return Response.json({ ok: true });
  if (path === "/old") return Response.redirect("/json", 301);
  if (path === "/echo" && method === "POST") {
    return new Response(body, {
      headers: { "content-type": "text/plain" },
    });
  }
  return new Response("not found", { status: 404 });
});
```

```sh theme={null}
ff server.js --allow-net=0.0.0.0:3000
curl http://127.0.0.1:3000/json        # {"ok":true}
curl -i http://127.0.0.1:3000/old      # 301 without Location (clients won't follow)
curl -X POST http://127.0.0.1:3000/echo -d hi  # hi
```

## Runtime config: `FF_ECHO`

`FF_ECHO` is read by the runtime, not by JavaScript, so it needs no
`--allow-env`. Setting any value (even empty) makes every request return
`200 {"message":"ok"}` without invoking your handler:

```sh theme={null}
FF_ECHO=1 ff server.js --allow-net=0.0.0.0:3000
```

The listener still needs its net grant — echo mode bypasses the handler, not
the permission check. See the [env guide](https://fairyfly.dev/guides/env.md#ff_echo--smoke-mode).

## Limits (summary)

Full table lives in the Limitations reference; the ones that bite here: 512 concurrent connections, 4 KB max HTTP/1.1 request headers (→ `431`), 1 MB max HTTP/1.1 request body (4 KB static buffer spills to the heap, 64 MB global spill budget; → `413` / `503`; HTTP/2 allows 10 MB per stream / 16 MB per session), 10 MB max response body (the 64 KB staging buffer spills to the heap), 30s read deadline (incomplete requests terminated), 30s handler watchdog (→ `504`), strict HTTP framing (ambiguous Content-Length/Transfer-Encoding, obs-fold, or BWS rejected with 400 Bad Request), Response status clamped to 100..999, plain listeners speak HTTP/1.1 (HTTP/2 needs TLS), bind is always `0.0.0.0`.

## See also

* [Permissions](https://fairyfly.dev/concepts/permissions.md) — flags, scopes, denial contract
* [HTTP Server guide](https://fairyfly.dev/guides/http-server.md) — tutorial version of this page
* [WebSocket guide](https://fairyfly.dev/guides/websocket.md) — `send` / `sendBinary` patterns
* [TLS guide](https://fairyfly.dev/guides/tls.md) — `tls: { cert, key }` in depth
* [Limitations](https://fairyfly.dev/reference/limitations.md) — every hard cap


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.