Store and serve files from a function
A function runtime can keep files as well as return them. With env.file it writes CSV exports, PDF receipts, generated images or archives to the distribution's file store and reads them back on later requests. Visitors reach a file through a public /_api path or a short-lived download link.
Each file is public or private. The prefix it is stored under decides which:
- Public files can be served on a
/_apipath by afileroute. - Private files are never served by a route. A visitor gets one only through a link that the function creates, valid for at most an hour. Use private for anything that belongs to one visitor, such as a receipt.
This page assumes acme-marketing (d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38) already has a compiled JavaScript function runtime, script 01M3RD5T2C8V7X1N4K6P9Q2W5Z. If not, start with Add an endpoint.
The web console does not manage function runtimes or file grants yet. Only an agent can grant a prefix; there is no HTTP route or CLI command for it.
1. Grant the function a prefix
A function can only use keys under a prefix you granted. The grant is stored outside the source, so the code cannot widen its own access.
On acme-marketing, give script 01M3RD5T2C8V7X1N4K6P9Q2W5Z read-write access to the
file prefix exports/* as public, and receipts/* as private.The agent runs edge_file_prefix_set once for each prefix. Each answer shows the prefix, mode, visibility and the scripts the grant covers. A grant with an empty script list covers every function on the distribution. Once a prefix's visibility is set, it cannot be changed. To move files between public and private, use a new prefix.
This does not change the live site. No visitor can reach the files yet.
2. Write files from the handler
function handler(request, env) {
const rows = [['id', 'total'], ['1', '42'], ['2', '17']];
const csv = rows.map((row) => row.join(',')).join('\n') + '\n';
const saved = env.file.put('exports/report.csv', csv, { contentType: 'text/csv' });
const receipt = new TextEncoder().encode('Receipt #1042\nTotal: 42\n');
env.file.put('receipts/1042.txt', receipt, { contentType: 'text/plain' });
const link = env.file.link('receipts/1042.txt', { ttlSeconds: 600 });
return {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ report: '/_api/exports/report.csv', size: saved.size, receipt: link.url }),
};
}In Python, the same calls are env.file.put("exports/report.csv", csv, content_type="text/csv") and env.file.link(key, ttl_seconds=600). They return dictionaries.
put creates a file. Replacing an existing file requires its current etag, so two requests cannot silently overwrite each other's writes:
const current = env.file.head('exports/report.csv');
env.file.put('exports/report.csv', csv, { contentType: 'text/csv', ifMatch: current && current.etag });A single call moves at most 4 MiB. For a larger file, open a writer and append the content in pieces:
const writer = env.file.create('exports/archive.zip', { contentType: 'application/zip' });
for (const chunk of chunks) writer.append(chunk);
const done = writer.commit(); // { etag, size }If a writer is still open when the handler returns, it is discarded and nothing is stored. If the handler also calls fetch, make those calls before you start writing.
3. Test before mapping a path
Invoke script 01M3RD5T2C8V7X1N4K6P9Q2W5Z on acme-marketing with GET /_api/report,
then list the files it wrote.The agent runs edge_function_invoke, then edge_file_list. The list shows each key with its visibility and size:
{
"items": [
{ "key": "exports/report.csv", "visibility": "public", "size": 20 },
{ "key": "receipts/1042.txt", "visibility": "private", "size": 25 }
]
}edge_file_get returns one of three things for a file: its metadata, its content (up to 4 MiB), or a download link valid for 15 minutes. edge_file_delete removes a file. Private files can contain visitor data, so read them only when you need to.
4. Serve the public prefix
This step changes what visitors can reach. Sending runtime replaces the whole endpoint map, so include every path you already have.
On acme-marketing, serve the public files under exports/ at /_api/exports/*,
and keep GET /_api/report on script 01M3RD5T2C8V7X1N4K6P9Q2W5Z.edge api PATCH /v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38 --input - <<'EOF'
{
"runtime": {
"api": {
"routes": [
{ "match": "/_api/exports/*", "file": "exports/" },
{ "match": "/_api/report", "wasm": "01M3RD5T2C8V7X1N4K6P9Q2W5Z", "methods": ["GET"] }
]
}
}
}
EOFcurl -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/exports/*","file":"exports/"},{"match":"/_api/report","wasm":"01M3RD5T2C8V7X1N4K6P9Q2W5Z","methods":["GET"]}]}}}'The agent runs edge_distribution_update. The paths go live as soon as the update compiles. Endpoints have no preview and no promote step. To withdraw a path, send the map again without it.
curl -sI https://acme-marketing.edge.deca-dev.com/_api/exports/report.csvImages, PDF, text, CSV, JSON, audio and video open in the browser. Every other type, including HTML and SVG, downloads as an attachment, so a stored file never runs as part of your site. A file larger than 4 MiB redirects to a download link valid for five minutes. The function can rewrite this prefix, so its files are served with cache-control: no-store.
Next
- Generate large files in the background
- Let signed-in visitors upload images
- Function runtimes: every
env.filecall and error code - Endpoints: rules for
fileroutes