Primate LogoPrimate
GuidesRequests

Read request body

Access the request body by calling methods on request.body. Methods validate that the body is of the correct type.

Text -> string

Use text() to get the body as a string.

// routes/api.ts
import route from "primate/route";

export default route({
  async post(request) {
    const received = await request.body.text();
    return { received };
  },
});

JSON -> Record

Use json() to get the body as JSON (Record).

// routes/api.ts
import route from "primate/route";

export default route({
  async post(request) {
    const received = await request.body.json();
    return { received };
  },
});

Form -> Record

Use form() to get the body as a form (Record<string, string>).

import route from "primate/route";

export default route({
  async post(request) {
    const received = await request.body.form();
    return { received };
  },
});

form() keeps the last value when a field name occurs more than once. Use formEntries() when repeated fields or their submission order matter. It returns a JSON-compatible array of [name, value] pairs.

const entries = await request.body.formEntries();
const categoryIds = entries
  .filter(([name]) => name === "categoryIds")
  .map(([, value]) => value);

Multipart -> Record

Use multipart() to get the body as a multpart form (Record<string, string | File>).

import route from "primate/route";

export default route({
  async post(request) {
    const { form, files } = await request.body.multipart();
    return { form };
  },
});

Binary -> Blob

Use binary() to get the body as binary (Blob).

// routes/api.ts
import route from "primate/route";

export default route({
  async post(request) {
    const blob = await request.body.blob();
    return { blob };
  },
});