Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท HTTP Servers and APIs

Headers, Cookies and Calling Other APIs with fetch

Set and read headers, handle CORS and cookies in Bun servers, and call other APIs with fetch: timeouts, retries, error handling and Bun-specific options.

Real APIs do more than return JSON. They add security and caching headers, answer cross-origin browser requests, set cookies for sessions, and call other services. This lesson covers those jobs in Bun. Everything is built on web standards (Headers, Response, fetch), so most of it carries over to other runtimes.

Reading and setting headers

req.headers is a Headers object. Names are case-insensitive. A response takes headers in its init argument or through res.headers.set().

TypeScript
Bun.serve({
  fetch(req) {
    const agent = req.headers.get("user-agent") ?? "unknown";
    const res = Response.json({ agent });
    res.headers.set("Cache-Control", "no-store");
    res.headers.set("X-Content-Type-Options", "nosniff");
    return res;
  },
});

Useful headers to set deliberately: Cache-Control (how long may it be cached), Content-Security-Policy for HTML, Strict-Transport-Security when you serve HTTPS, Location with a 3xx status for redirects (Response.redirect(url, 302) does it for you), and Content-Disposition: attachment; filename="report.csv" to force a download.

The client address is not in the headers. Bun gives it to you through the second argument of fetch:

TypeScript
Bun.serve({
  fetch(req, server) {
    const ip = server.requestIP(req); // { address, family, port } or null
    return new Response(`You are ${ip?.address}`);
  },
});

Behind a proxy, requestIP is the proxy's address. Read X-Forwarded-For only if you trust that proxy to set it.

CORS

A browser page on https://app.example.com that calls your API on https://api.example.com triggers a cross-origin request. The browser sends a preflight OPTIONS request first for anything beyond simple calls and refuses to expose the response unless your server answers with the right Access-Control-* headers.

TypeScript
const cors = {
  "Access-Control-Allow-Origin": "https://app.example.com",
  "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
  "Access-Control-Max-Age": "86400",
};

function withCors(handler: (req: Request) => Response | Promise<Response>) {
  return async (req: Request) => {
    if (req.method === "OPTIONS") return new Response(null, { status: 204, headers: cors });
    const res = await handler(req);
    for (const [k, v] of Object.entries(cors)) res.headers.set(k, v);
    return res;
  };
}

A wrapper function like withCors is the Bun way to do "middleware": higher-order functions that take a handler and return a handler. Prefer an explicit origin to *, and never combine * with credentials.

Node.js A middleware wrapper and CORS headers (plain Web APIs)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Cookies

Cookies carry small pieces of state between requests, most often a session id. In Bun route handlers, req.cookies is a CookieMap with get, set, delete and has; changes made to it are added to the response as Set-Cookie headers automatically.

TypeScript
Bun.serve({
  routes: {
    "/login": {
      POST: async (req) => {
        const sessionId = crypto.randomUUID();
        req.cookies.set("session", sessionId, {
          httpOnly: true,
          secure: true,
          sameSite: "lax",
          maxAge: 60 * 60 * 24, // seconds
          path: "/",
        });
        return Response.json({ ok: true });
      },
    },
    "/me": (req) => {
      const id = req.cookies.get("session");
      return id ? Response.json({ session: id }) : new Response("Unauthorized", { status: 401 });
    },
  },
});

Always set httpOnly (JavaScript cannot read the cookie, which blunts XSS theft), secure (HTTPS only) and sameSite (lax or strict to limit cross-site sending). The cookie holds a random id; the data lives on the server, for example in SQLite. If your Bun version does not expose req.cookies, build the header by hand: new Response(body, { headers: { "Set-Cookie": "session=abc; HttpOnly; Secure; SameSite=Lax; Path=/" } }) and parse req.headers.get("cookie").

Node.js Parsing and building Set-Cookie by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Calling other APIs with fetch

Bun implements the standard fetch and adds speed plus a few extras. A robust call checks res.ok, sets a timeout and handles errors:

TypeScript
async function getJson<T>(url: string): Promise<T> {
  const res = await fetch(url, {
    headers: { Accept: "application/json" },
    signal: AbortSignal.timeout(5000), // abort after 5 seconds
  });
  if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${url}`);
  return (await res.json()) as T;
}

fetch only rejects on network failure or abort, not on 404 or 500, so the res.ok check is essential. Common patterns:

  • POST JSON: fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }).
  • Retry with backoff: loop a few times, wait 2 ** attempt * 100 ms (await Bun.sleep(ms)), retry only on network errors and 5xx, never on 4xx.
  • Parallel calls: await Promise.all([getJson(a), getJson(b)]) runs them together.
  • Bun extras: a proxy option, tls settings, unix: "/path/to.sock" to talk over a Unix socket, and fetch("file:///...")-style local reads are supported in some forms; check the docs for your Bun version before relying on them.
Node.js A fetch helper with retry and a timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which cookie attribute stops page JavaScript from reading the cookie?

    HttpOnly hides the cookie from document.cookie, which limits damage from XSS.
  2. 2. When does fetch reject its promise?

    A 404 or 500 still resolves. Check res.ok yourself.
  3. 3. What is the idiomatic way to share logic such as CORS across Bun handlers?

    Handlers are plain functions, so higher-order wrapper functions compose naturally.
  4. 4. How do you get the client's IP address inside a fetch(req, server) handler?

    server.requestIP(req) returns the socket address, or null. Behind a proxy it is the proxy's address.

Summary

  • Headers are a standard Headers object; set caching and security headers on purpose.
  • CORS needs an OPTIONS preflight answer plus Access-Control-* headers on real responses.
  • Cookies: random session id, httpOnly, secure, sameSite; data stays on the server.
  • fetch does not reject on HTTP errors: check res.ok, add AbortSignal.timeout, retry only 5xx and network errors.
  • "Middleware" in Bun is just handler wrappers.

Next: Streaming Responses and Server-Sent Events