Skip to content

Let signed-in visitors upload images ​

A function runtime can let a visitor upload a file straight to storage. The function decides whether to allow the upload and then signs it with env.upload. The visitor's browser sends the file to storage with the ticket it gets back, so the file never passes through the function. Edge then scans the file for malware and checks that its first bytes match the declared type. Only once the scan comes back clean can the function read the file or keep it in the distribution's file store, where a file route can serve it.

This page builds a profile-photo upload. The page talks to three paths on one function:

  1. POST /_api/avatar/sign checks the request and returns an upload ticket.
  2. GET /_api/avatar/status/{upload_id} reports the scan.
  3. POST /_api/avatar/keep copies the clean image to avatars/ in the file store.

A file route then serves the kept images at /_api/avatars/*.

This page assumes acme-community (7c1e4b9a-2d5f-4e83-a6b0-9f3d8c2e1a57) is live, already serves the data object members.json at GET /_api/members, and has a compiled JavaScript function runtime, script 01M5BX8R3K7N2Q9V4T6W1Y3Z5C. If it has no function yet, start with Add an endpoint.

The web console does not manage function runtimes or their grants yet. Only an agent can grant uploads and file prefixes; there is no HTTP route or CLI command for either.

Before you start: require sign-in ​

A function does not receive the visitor's cookies, headers or identity, so it cannot tell one visitor from another. To limit uploads to signed-in visitors, put the whole distribution behind visitor sign-in. Edge then refuses every /_api request without a valid sign-in, so only signed-in visitors ever reach the function. See Password-protect a distribution and the rules in Access control.

Inside the function, check what you can see in the request before signing: the declared type and size, and anything else your own logic needs. Edge adds its own checks on top: the type must be on the allowed list, the file must arrive at exactly the declared size, and only the script that signed an upload can look at it afterwards.

1. Let the function sign uploads ​

Uploads are off for every script until you turn them on. The setting is stored outside the source, so the code cannot grant itself uploads.

text
On acme-community, let script 01M5BX8R3K7N2Q9V4T6W1Y3Z5C sign visitor uploads.

The agent runs edge_function_upload_grant_set with enabled true. The answer lists every script on the distribution that can sign uploads:

json
{ "script_id": "01M5BX8R3K7N2Q9V4T6W1Y3Z5C", "uploads": true, "upload_scripts": ["01M5BX8R3K7N2Q9V4T6W1Y3Z5C"] }

edge_file_prefix_get shows the same list as upload_scripts. To stop a script signing, ask the agent to turn uploads off for it; it runs the same tool with enabled false. Without the grant, every env.upload call fails with not_granted.

This does not change the live site. No visitor can upload until a route runs the script.

2. Grant a public prefix for the kept images ​

keep writes into the file store, so the script also needs a read-write grant on the prefix it keeps images under. Make it public so a file route can serve the images.

text
On acme-community, give script 01M5BX8R3K7N2Q9V4T6W1Y3Z5C read-write access to the
file prefix avatars/* as public.

The agent runs edge_file_prefix_set. A prefix's visibility cannot change once it is set. See Store and serve files from a function for how file grants work.

3. Write the handler ​

One handler serves all three paths. It accepts JPEG and PNG up to 5 MiB, which is the function's own rule; Edge allows larger files and more types.

javascript
const MAX_BYTES = 5 * 1024 * 1024;
const EXTENSIONS = { 'image/jpeg': 'jpg', 'image/png': 'png' };
const STATUS_FOR = { not_found: 404, not_clean: 409, precondition_failed: 409, type_mismatch: 422, quota_exceeded: 403 };

function reply(statusCode, value) {
  return { statusCode, headers: { 'content-type': 'application/json' }, body: JSON.stringify(value) };
}

function handler(request, env) {
  try {
    if (request.method === 'POST' && request.path === '/_api/avatar/sign') {
      const { contentType, size } = JSON.parse(request.body || '{}');
      if (!EXTENSIONS[contentType]) return reply(400, { error: 'jpeg_or_png_only' });
      if (!(size >= 1 && size <= MAX_BYTES)) return reply(400, { error: 'too_large' });
      return reply(200, env.upload.sign({ contentType, size }));
    }

    if (request.method === 'GET' && request.path.startsWith('/_api/avatar/status/')) {
      const uploadId = request.path.slice('/_api/avatar/status/'.length);
      const { status, reason } = env.upload.status(uploadId);
      return reply(200, { status, reason });
    }

    if (request.method === 'POST' && request.path === '/_api/avatar/keep') {
      const { uploadId } = JSON.parse(request.body || '{}');
      const { contentType } = env.upload.status(uploadId);
      const kept = env.upload.keep(uploadId, `avatars/${uploadId}.${EXTENSIONS[contentType]}`);
      return reply(200, { url: `/_api/${kept.key}`, size: kept.size });
    }

    return reply(404, { error: 'not_found' });
  } catch (error) {
    if (!error.code) throw error;
    return reply(STATUS_FOR[error.code] || 400, { error: error.code });
  }
}
  • sign returns the ticket the browser needs. Pass it to the page as it is: its field names are snake_case because the page reads them.
  • keep creates a file and never replaces one. Each image is named after its upload id, so every upload gets its own key. Because the function cannot see who the visitor is, record which image belongs to whom in your own system.
  • An upload that is never kept is deleted after a day.
  • The handler makes at most two upload calls per request, well inside the eight host calls an invocation may make.

In Python the handler is def handler(request, env) and the calls are env.upload.sign(content_type, size), env.upload.status(upload_id) and env.upload.keep(upload_id, key). They return dictionaries, and errors are raised as UploadError with .code.

4. Test before mapping a path ​

text
Invoke script 01M5BX8R3K7N2Q9V4T6W1Y3Z5C on acme-community with POST /_api/avatar/sign
and the body {"contentType": "image/jpeg", "size": 248311}.

The agent runs edge_function_invoke. The response body is a ticket:

json
{
  "upload_id": "upl_01M5C2H7QK3R8T1V6W9X4Y2Z5B",
  "mode": "single",
  "url": "https://…",
  "fields": { "key": "…", "Content-Type": "image/jpeg", "Policy": "…", "X-Amz-Signature": "…", … },
  "expires_in": 600
}

A test ticket counts toward your organization's monthly upload quota like any other, and expires unused.

5. Map the paths ​

This step changes what visitors can reach. Sending runtime replaces the whole endpoint map, so include every path you already have.

text
On acme-community, map POST /_api/avatar/sign, GET /_api/avatar/status/* and
POST /_api/avatar/keep to script 01M5BX8R3K7N2Q9V4T6W1Y3Z5C, serve the public files
under avatars/ at /_api/avatars/*, and keep GET /_api/members serving members.json.
bash
edge api PATCH /v1/distributions/7c1e4b9a-2d5f-4e83-a6b0-9f3d8c2e1a57 --input - <<'EOF'
{
  "runtime": {
    "api": {
      "routes": [
        { "match": "/_api/members", "document": "members.json" },
        { "match": "/_api/avatar/sign", "wasm": "01M5BX8R3K7N2Q9V4T6W1Y3Z5C", "methods": ["POST"] },
        { "match": "/_api/avatar/status/*", "wasm": "01M5BX8R3K7N2Q9V4T6W1Y3Z5C", "methods": ["GET"] },
        { "match": "/_api/avatar/keep", "wasm": "01M5BX8R3K7N2Q9V4T6W1Y3Z5C", "methods": ["POST"] },
        { "match": "/_api/avatars/*", "file": "avatars/" }
      ]
    }
  }
}
EOF
bash
curl -s -X PATCH \
  https://api.edge.deca-dev.com/v1/distributions/7c1e4b9a-2d5f-4e83-a6b0-9f3d8c2e1a57 \
  -H "Authorization: Bearer $EDGE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"runtime":{"api":{"routes":[{"match":"/_api/members","document":"members.json"},{"match":"/_api/avatar/sign","wasm":"01M5BX8R3K7N2Q9V4T6W1Y3Z5C","methods":["POST"]},{"match":"/_api/avatar/status/*","wasm":"01M5BX8R3K7N2Q9V4T6W1Y3Z5C","methods":["GET"]},{"match":"/_api/avatar/keep","wasm":"01M5BX8R3K7N2Q9V4T6W1Y3Z5C","methods":["POST"]},{"match":"/_api/avatars/*","file":"avatars/"}]}}}'

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.

6. Upload from the page ​

The function only sees the request path, not a query string, so the page puts the upload id in the path when it asks for the status. A POST to /_api with a body must also carry x-amz-content-sha256, the hex SHA-256 of the body.

html
<input id="avatar" type="file" accept="image/jpeg,image/png">
<img id="preview" alt="">
javascript
async function api(method, path, body) {
  const init = { method, headers: {} };
  if (body !== undefined) {
    const text = JSON.stringify(body);
    const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
    init.headers['content-type'] = 'application/json';
    init.headers['x-amz-content-sha256'] = [...new Uint8Array(digest)]
      .map((byte) => byte.toString(16).padStart(2, '0')).join('');
    init.body = text;
  }
  const r = await fetch(path, init);
  const data = await r.json();
  if (!r.ok) throw data;
  return data;
}

async function uploadAvatar(file) {
  // 1. Ask the function for a ticket.
  const ticket = await api('POST', '/_api/avatar/sign', { contentType: file.type, size: file.size });

  // 2. Send the file to storage: every ticket field first, the file last.
  const data = new FormData();
  for (const [key, value] of Object.entries(ticket.fields)) data.append(key, value);
  data.append('file', file);
  const sent = await fetch(ticket.url, { method: 'POST', body: data });
  if (!sent.ok) throw new Error('upload failed');

  // 3. Wait for the scan.
  for (;;) {
    const { status, reason } = await api('GET', `/_api/avatar/status/${ticket.upload_id}`);
    if (status === 'clean') break;
    if (status === 'rejected' || status === 'scan_failed') throw new Error(reason || status);
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }

  // 4. Keep it and show it.
  const kept = await api('POST', '/_api/avatar/keep', { uploadId: ticket.upload_id });
  document.getElementById('preview').src = kept.url;
  return kept.url;
}

document.getElementById('avatar').addEventListener('change', (event) => {
  uploadAvatar(event.target.files[0]).catch((error) => console.error(error));
});

The ticket is valid for 10 minutes. Storage refuses a file of any length other than the size the page declared, so send the File the visitor picked rather than a re-encoded copy.

status moves through these values:

statusMeaning
pendingThe ticket was issued but the file has not arrived
scanningThe file arrived and is being scanned
cleanNo malware, and the first bytes match the declared type. The function can read or keep it.
rejectedreason is malware, or type_mismatch when the first bytes are not the declared type
scan_failedNo verdict. The file can never be read or kept.

Calling keep before the upload is clean fails with not_clean, or type_mismatch for a file whose contents are not the declared type. This handler answers those as 409 and 422.

bash
curl -sI https://acme-community.edge.deca-dev.com/_api/avatars/upl_01M5C2H7QK3R8T1V6W9X4Y2Z5B.jpg

Kept images open in the browser. Like every file route on a prefix a function can write, they are served with cache-control: no-store.

Files over 100 MiB do not come back as a single ticket. They come as a multipart ticket of 16 MiB parts, which the page PUTs one by one and then hands back to the function to finish with env.upload.complete. See Function runtimes.

Next ​