Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท HTTP Servers and APIs

Request Bodies: JSON, Forms and Uploads

Read request bodies in Bun.serve: req.json, req.text, req.formData, multipart file uploads, body size limits and input validation, with runnable Node stand-ins.

GET requests carry everything in the URL. POST, PUT and PATCH requests carry a body, and the Content-Type header says how to read it. Because Bun uses the standard Request class, reading a body is the same handful of methods you know from the browser: json(), text(), formData(), arrayBuffer(), blob() and bytes(). Each one returns a promise and can be used once per request, because the body is a stream that is consumed as you read it.

JSON bodies

TypeScript
Bun.serve({
  routes: {
    "/api/users": {
      POST: async (req) => {
        let body: unknown;
        try {
          body = await req.json();
        } catch {
          return Response.json({ error: "Invalid JSON" }, { status: 400 });
        }
        // body is `unknown`: validate before trusting it
        return Response.json({ received: body }, { status: 201 });
      },
    },
  },
});

req.json() throws if the body is empty or not valid JSON. Wrap it in try/catch and answer 400 Bad Request; otherwise a client typo becomes a 500 error in your logs.

Validate, do not trust

TypeScript types disappear at runtime. A client can send anything, so check shape and types yourself, or with a validator library such as Zod (bun add zod).

TypeScript
function parseNewUser(input: unknown): { name: string; age: number } | string {
  if (typeof input !== "object" || input === null) return "Body must be an object";
  const { name, age } = input as Record<string, unknown>;
  if (typeof name !== "string" || name.trim() === "") return "name is required";
  if (typeof age !== "number" || !Number.isInteger(age) || age < 0) return "age must be a whole number";
  return { name: name.trim(), age };
}

Returning either a value or an error string keeps the route tiny: if the result is a string, send 400 with it; otherwise carry on.

Node.js Reading and validating a JSON body (Node stand-in)

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.

Forms: urlencoded and multipart

HTML forms send application/x-www-form-urlencoded (simple fields) or multipart/form-data (fields plus files). req.formData() parses both into a standard FormData object:

TypeScript
Bun.serve({
  routes: {
    "/signup": {
      POST: async (req) => {
        const form = await req.formData();
        const email = form.get("email");
        const avatar = form.get("avatar"); // string | File | null

        if (typeof email !== "string" || !email.includes("@")) {
          return new Response("Bad email", { status: 400 });
        }
        if (avatar instanceof File && avatar.size > 0) {
          await Bun.write(`./uploads/${crypto.randomUUID()}.bin`, avatar);
        }
        return new Response("Welcome " + email);
      },
    },
  },
});

A File from a form is a Blob with a name, type, size and the usual text(), bytes() and stream() methods. Bun.write(path, file) writes it to disk efficiently (more in Bun.file and Bun.write). Never use the client's file.name as a path: it may contain ../. Generate your own name, as above, and check file.type and file.size against an allow-list.

Node.js Parsing a multipart form (Node 24 built-ins)

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.

Limits and raw bodies

Bun rejects bodies larger than maxRequestBodySize (128 MB by default) with 413 Payload Too Large. Lower it to what your API needs:

TypeScript
Bun.serve({
  maxRequestBodySize: 1024 * 1024, // 1 MB
  fetch(req) {
    return new Response("ok");
  },
});

For binary data use req.arrayBuffer() or req.bytes(). To process a huge upload without holding it in memory, read req.body, a ReadableStream, chunk by chunk with for await (const chunk of req.body). Remember the one-read rule: if you need the body twice (for example to log and parse it), call req.clone() before reading.

Query strings

Query parameters live in the URL, not the body: new URL(req.url).searchParams. Use .get() for one value, .getAll() for repeated keys like ?tag=a&tag=b, and always provide defaults and bounds for things like limit and page.

TypeScript
const url = new URL(req.url);
const page = Math.max(1, Number(url.searchParams.get("page")) || 1);
const limit = Math.min(100, Number(url.searchParams.get("limit")) || 20);

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if you call req.json() and then req.text() on the same request?

    A request body is a stream that can be read once. Use req.clone() first if you need it twice.
  2. 2. Which method parses both urlencoded and multipart form posts?

    formData() returns a standard FormData object for both form encodings.
  3. 3. Why should you not save an uploaded file under file.name?

    A hostile client can send a name such as ../../etc/x. Generate your own safe name.
  4. 4. Which status fits a request whose JSON body cannot be parsed?

    The client sent a bad request, so answer 400 rather than letting it surface as a server error.

Summary

  • Use req.json(), req.text(), req.formData(), req.arrayBuffer(); each body is readable once.
  • Catch parse errors and answer 400; validate shape and types before using data.
  • Uploaded File objects work with Bun.write; never trust file.name, check type and size.
  • maxRequestBodySize caps request size; stream req.body for huge uploads.
  • Query strings come from new URL(req.url).searchParams.

Next: Headers, Cookies and Calling Other APIs with fetch