Skip to content

Return a file from a function ​

A function runtime can answer with a file instead of text: a CSV export, a PDF receipt, a generated image. The visitor's browser gets the bytes with the content type you set, and content-disposition decides whether it opens inline or downloads.

This page assumes a distribution that is already live, with function runtimes you can create. Throughout, that distribution is acme-marketing (d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38). If you have not built a function runtime before, start with Add an endpoint.

Function runtimes are not managed in the web console yet. Create and test them through your agent.

1. Write a handler that returns bytes ​

Set a content-type header and return the bytes as the body. In JavaScript that is a Uint8Array (or ArrayBuffer):

javascript
// report.js
function handler(request) {
  const rows = [['id', 'total'], ['1', '42'], ['2', '17']];
  const csv = new TextEncoder().encode(rows.map((row) => row.join(',')).join('\n') + '\n');
  return {
    headers: {
      'content-type': 'text/csv',
      'content-disposition': 'attachment; filename="report.csv"',
    },
    body: csv,
  };
}

In Python, return bytes:

python
def handler(request):
    csv = "id,total\n1,42\n2,17\n".encode()
    return {
        "headers": {
            "content-type": "text/csv",
            "content-disposition": 'attachment; filename="report.csv"',
        },
        "body": csv,
    }

Rust, TinyGo, C and AssemblyScript write the envelope themselves: add "bodyEncoding":"base64" and put base64 of the bytes in body.

The content-type header is required. Without it the visitor gets a generic 500 and the reason is in the function's logs. The decoded file may be up to 4 MiB.

2. Create it and wait for the build ​

text
On the acme-marketing distribution, create a JavaScript function runtime from
report.js. Do not map a public /_api path yet. Tell me the script id when the
build succeeds.

The agent runs edge_function_create, then polls edge_function_get until the build is succeeded. The live site is unchanged. This page uses 01M3RD5T2C8V7X1N4K6P9Q2W5Z as the script id; yours will be different.

3. Check the file before anyone can reach it ​

text
Invoke script 01M3RD5T2C8V7X1N4K6P9Q2W5Z on acme-marketing with GET /_api/report
and decode the body.

The agent runs edge_function_invoke. The result has body_encoding: "base64" and the file as base64 in body:

json
{
  "status_code": 200,
  "headers": { "content-type": "text/csv", "content-disposition": "attachment; filename=\"report.csv\"" },
  "body": "aWQsdG90YWwKMSw0MgoyLDE3Cg==",
  "body_encoding": "base64",
  "fuel_used": 61204,
  …
}

Returning the bytes is cheap at any size. Building them is not always: a byte-by-byte loop in JavaScript or Python burns fuel quickly, so if a large file fails with fuel_exhausted, build it from whole strings or arrays (TextEncoder, new Uint8Array(n), bytes(n)).

4. Map it on /_api ​

This is the step that changes what visitors can reach. Sending runtime replaces the whole endpoint map, so keep your existing endpoints in the same update.

text
Map GET /_api/report on acme-marketing to script 01M3RD5T2C8V7X1N4K6P9Q2W5Z.
Keep every existing endpoint.
bash
edge api PATCH /v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38 --input - <<'EOF'
{
  "runtime": {
    "api": {
      "routes": [
        { "match": "/_api/report", "wasm": "01M3RD5T2C8V7X1N4K6P9Q2W5Z", "methods": ["GET"] }
      ]
    }
  }
}
EOF
bash
curl -s -X PATCH \
  https://api.edge.deca-dev.com/v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38 \
  -H "Authorization: Bearer $EDGE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"runtime":{"api":{"routes":[{"match":"/_api/report","wasm":"01M3RD5T2C8V7X1N4K6P9Q2W5Z","methods":["GET"]}]}}}'

The agent runs edge_distribution_update. The new path is live as soon as the update compiles; there is no preview or promote step for endpoints. To take it down, send the endpoint map again without it.

Then download it:

bash
curl -sO -J https://acme-marketing.edge.deca-dev.com/_api/report

-J saves it as report.csv, the name from content-disposition.

Read a binary request body ​

A request whose content-type is not text (for example image/png or application/pdf) reaches the handler as base64, with request.bodyEncoding set to "base64". Text bodies (text/*, JSON, XML, forms, or no content type) arrive as text with "utf8".

javascript
function handler(request, env) {
  const bytes = request.bodyEncoding === 'base64'
    ? env.base64.decode(request.body)
    : new TextEncoder().encode(request.body || '');
  return { headers: { 'content-type': 'application/json' }, body: JSON.stringify({ size: bytes.length }) };
}

Request bodies are capped at 1 MiB, and a POST or PUT must send x-amz-content-sha256 as the lowercase hex SHA-256 of the body. To test with a binary body before mapping a path, ask your agent to invoke with body_encoding: "base64".

Next ​