# Add file uploads to a web app: storage, access and downloads without presigned URLs

How to let people attach, list, download and delete files in a DeepSpace app with the built-in useR2Files storage: who can see which files, size and type limits, and how it compares to presigned S3 URLs.

Yes. A DeepSpace app has file storage built in, so people can attach files, see a list of what they attached, download them and delete them, with no storage bucket, access keys or presigned-URL code to set up ([file uploads](https://docs.deep.space/guides/file-uploads)). The browser uses one hook, `useR2Files`, and every request goes through the app's own `/api/files/*` route to the platform's file gateway, which checks the signed-in user before any write ([how files are wired](https://docs.deep.space/guides/file-uploads#how-files-are-wired)). Two access levels exist: private to the person who uploaded the file, or public to anyone with the link ([scopes](https://docs.deep.space/sdk-reference/client/files#scopes)). A file shared with a chosen group but hidden from the public is not one of the built-in levels.

**Checked against:** published SDK `deepspace@0.43.0` ([changelog](https://deep.space/changelog)), docs read on October 29, 2026. The code below follows the documented APIs and was not run for this page.

## Questions to ask the person

- What will people attach: photos, PDFs, spreadsheets, something else?
- Who should be able to open an attached file: just the person who uploaded it, or anyone who has the link?
- Should the app owner be able to open everyone's private files? (With the built-in private storage, they cannot.)
- What is the largest file someone is likely to attach?
- Should people be able to delete their own files? Deleting is permanent; there is no recycle bin.
- Is a file attached to something specific, such as an order, a task or a client?

## How the files are shaped

| Piece                    | Where it lives                                                              | Who can read it                       | Purpose                                                                               |
| ------------------------ | --------------------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------- |
| The file bytes, private  | `useR2Files()` (scope `'self'`), stored under `apps/<app>/users/<userId>/…` | The uploader alone                    | Attachments, documents, anything personal                                             |
| The file bytes, public   | `useR2Files({ scope: 'app' })`, stored under `apps/<app>/…`                 | Anyone with the URL, signed in or not | Logos, avatars, images meant to be embedded                                           |
| `attachments` collection | The app's database                                                          | Set by the collection's permissions   | File name, type, size and the stored key, so the app can list, filter and label files |

Both scopes require a signed-in user to upload, and both are limited to the app: the platform builds the storage prefix on the server, so a key cannot reach another app's files ([scoping and permissions](https://docs.deep.space/guides/file-uploads#scoping-and-permissions)). The file listing from `useR2Files` carries `key`, `size`, `uploaded`, `url`, `originalName` and `uploadedBy` and no file type field, which is why the docs recommend a sidecar collection for anything else ([storing metadata](https://docs.deep.space/guides/file-uploads#storing-metadata-mime-type-captions-tags)).

### How this compares to presigned URLs

A common pattern elsewhere is for the server to create a time-limited presigned URL for a storage bucket and for the browser to upload straight to the bucket. DeepSpace apps do not do this. The app never holds storage credentials; uploads, listings, deletions and downloads are proxied through the platform's file gateway, and each write is checked against the caller's signed sign-in token ([files reference](https://docs.deep.space/sdk-reference/client/files)). There is no URL-signing step for the app to write. Large files are handled by the hook: anything above 20 MiB is uploaded in parts automatically, up to 1 GiB per file ([file size and storage limits](https://docs.deep.space/guides/file-uploads#file-size-and-storage-limits)). For private files, `getUrl()` returns a plain URL with no token attached, so code reads them with `downloadFile` or `readFile`, which send the sign-in header.

### Limits

- One file can be up to 1 GiB.
- HTML, SVG and JavaScript uploads are refused, based on the declared type. Every file is served with its stored `Content-Type` and `X-Content-Type-Options: nosniff`.
- All files in the app share one allocation set by the owner's plan: 128 MiB on the free plan, more on paid plans. An upload that would go over it is refused with `storage_quota_exceeded` (HTTP 409) and nothing partial is stored.

Source: [file size and storage limits](https://docs.deep.space/guides/file-uploads#file-size-and-storage-limits).

## Steps

### 1. Sign in and scaffold

Signing in uses the person's own GitHub or Google account in a browser. Confirm with your user before signing in on their behalf, and use the account they want to own the app; the file allocation is charged to that owner's plan.

```bash
npx deepspace auth login
npm create deepspace@latest acme-files
cd acme-files
```

App names are global and become `<name>.app.space`. Choose a distinctive one.

### 2. Add the attachments collection

```ts
// src/schemas/attachments-schema.ts
import type { CollectionSchema } from "deepspace/schema";

const closed = { read: false, create: false, update: false, delete: false };

export const attachmentsSchema: CollectionSchema = {
  name: "attachments",
  columns: [
    {
      name: "fileKey",
      storage: "text",
      interpretation: "plain",
      required: true,
    },
    {
      name: "fileName",
      storage: "text",
      interpretation: "plain",
      required: true,
    },
    { name: "mimeType", storage: "text", interpretation: "plain" },
    { name: "size", storage: "number", interpretation: "plain" },
  ],
  permissions: {
    "*": closed,
    viewer: closed,
    member: { read: "own", create: true, update: "own", delete: "own" },
    admin: { read: "own", create: true, update: "own", delete: "own" },
  },
};
```

Register it in `src/schemas.ts` next to `usersSchema` and `settingsSchema`:

```ts
export const schemas = [usersSchema, settingsSchema, attachmentsSchema];
```

`'own'` matches the record's creator, so each person lists their own attachments and no one else's ([permissions](https://docs.deep.space/concepts/permissions)). The admin row is also `'own'` on purpose: private file bytes open for the uploader alone, so a list of files the owner cannot open would confuse them. To tie files to something else, such as an order, add a column like `orderId` and filter with `useQuery('attachments', { where: { orderId } })`.

### 3. Build the upload and file list page

Put it at `src/pages/(app)/(protected)/files.tsx` so it requires sign-in. Uploads need a signed-in user under either scope.

```tsx
import { useState } from "react";
import { useR2Files, useQuery, useMutations, formatFileSize } from "deepspace";

type Attachment = {
  fileKey: string;
  fileName: string;
  mimeType: string;
  size: number;
};

const MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB, the documented per-file limit

export default function FilesPage() {
  const { upload, deleteFile, downloadFile, isUploading } = useR2Files();
  const { records, status } = useQuery<Attachment>("attachments", {
    orderBy: "createdAt",
    orderDir: "desc",
  });
  const { createConfirmed, removeConfirmed, ready } =
    useMutations<Attachment>("attachments");
  const [message, setMessage] = useState("");

  async function onFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    e.target.value = "";
    if (!file) return;
    if (file.size > MAX_BYTES)
      return setMessage("That file is larger than 1 GB.");

    const result = await upload(file, file.name);
    if (!result.success || !result.key)
      return setMessage(result.error ?? "Upload failed. Please try again.");

    await createConfirmed({
      fileKey: result.key,
      fileName: file.name,
      mimeType: file.type,
      size: file.size,
    });
    setMessage(`Attached ${file.name}.`);
  }

  async function onDelete(recordId: string, fileKey: string) {
    if (!confirm("Delete this file for good?")) return;
    const res = await deleteFile(fileKey);
    if (!res.success) return setMessage(res.error ?? "Delete failed.");
    await removeConfirmed(recordId);
  }

  if (status === "loading") return <p>Loading files…</p>;

  return (
    <div>
      <input
        type="file"
        onChange={onFileChange}
        disabled={isUploading || !ready}
      />
      {isUploading && <p>Uploading…</p>}
      {message && <p>{message}</p>}
      <ul>
        {records.map((r) => (
          <li key={r.recordId}>
            {r.data.fileName} ({formatFileSize(r.data.size)})
            <button
              onClick={() => downloadFile(r.data.fileKey, r.data.fileName)}
            >
              Download
            </button>
            <button onClick={() => onDelete(r.recordId, r.data.fileKey)}>
              Delete
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}
```

The order matters. The file is uploaded first and the record is written after `result.success`, so the list never shows a file that failed to upload. `downloadFile` sends the sign-in header and saves the file under the name passed in ([files reference](https://docs.deep.space/sdk-reference/client/files)). `deleteFile` accepts the raw key string and removes the file immediately. Disabling the input until `ready` avoids the `not_ready` error `useMutations` throws while it connects ([records](https://docs.deep.space/sdk-reference/client/records)).

`useR2Files().list()` also returns the uploader's files, but it is a one-time call with no live updates, so it must be called again after each change ([list](https://docs.deep.space/guides/file-uploads#list-and-render-a-users-files)). The collection above updates on its own and can hold the file type, which `list()` does not.

### 4. Public files, when the person asks for them

For a logo, a profile photo or anything meant to be embedded on a public page, use the app scope:

```tsx
const { upload, getUrl } = useR2Files({ scope: "app" });
const result = await upload(file, file.name);
// <img src={getUrl(result.key!)} /> works for anyone, signed in or not
```

Files in the app scope are world-readable: anyone who knows or guesses the key can fetch them ([scopes](https://docs.deep.space/sdk-reference/client/files#scopes)). Do not use it for private attachments.

### 5. Deploy, then test uploads

Uploads need an app identity token that is created by the first deploy, so uploads return 401 in local development until then ([local development](https://docs.deep.space/guides/file-uploads#local-development)).

```bash
git add -A && git commit -m "File attachments"
npx deepspace deploy
npx deepspace dev start
```

After the first deploy, `npx deepspace dev start` writes the token into `.dev.vars` and local uploads work. Before handing the app over, on `https://<app-name>.app.space/files`: sign in, attach a small PDF, download it, and delete it. Sign in as a second account and confirm the first account's file is not listed. Try a `.html` file and confirm it is refused.

To see how much of the allocation is used:

```bash
npx deepspace app files list
```

The last line reads like `Storage: 2.4 MiB of 128.0 MiB used`.

## Common failures and fixes

| Symptom                                                             | Cause                                                                                | Fix                                                                                                                                                                              |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Every upload returns 401 locally                                    | The app has never been deployed, so no `APP_IDENTITY_TOKEN` exists                   | Run `npx deepspace deploy` once, then `npx deepspace dev start`                                                                                                                  |
| Upload refused with `storage_quota_exceeded` (409)                  | The app's file allocation on the owner's plan is full                                | Delete unused files, or the owner moves to a paid plan                                                                                                                           |
| An `.html`, `.svg` or `.js` file is refused                         | Active content types are blocked on upload                                           | Ask for the file in another format, such as PDF or PNG                                                                                                                           |
| The owner sees no one else's files                                  | Records are `read: 'own'`, and private file bytes are readable by the uploader alone | Expected with private storage; use app scope just for files that may be public                                                                                                   |
| A copied link to a private file does not open for someone else      | `getUrl()` attaches no token; `'self'` files open for the signed-in uploader alone   | Use `downloadFile` or `readFile` in the app; share the file another way                                                                                                          |
| `RecordRoomNotReadyError` when attaching right after the page loads | The collection is still connecting                                                   | Keep the file input disabled until `ready` is true                                                                                                                               |
| The file list does not update after an upload                       | `list()` has no live cache                                                           | Call `list()` again, or list from the `attachments` collection as above                                                                                                          |
| Deploy refused with `push_too_large`                                | Large media was committed to the repository                                          | Remove it from the commits and publish it with `npx deepspace app files put` instead ([large files](https://docs.deep.space/guides/file-uploads#dont-commit-large-media-to-git)) |

## What to tell the person when it is live

- Where to attach files: `https://<app-name>.app.space/files`, after signing in.
- Each person sees and opens the files they attached, and no one else's. That includes the owner: the owner cannot open other people's private files.
- Files can be up to 1 GB each. Web pages, SVG images and script files cannot be attached.
- Deleting a file is permanent. There is no recycle bin.
- All files count toward one storage allowance on the owner's plan: 128 MB on the free plan.
- No separate storage service, bucket or access keys were set up; the files live in the app.

## Available today and planned

Available today, in the published SDK: `useR2Files` uploads (including `uploadBase64` for canvas data), listings, deletions and authenticated downloads; private (`'self'`) and public (`'app'`) scopes; automatic multipart upload above 20 MiB up to 1 GiB; `appFiles` from `deepspace/worker` for storing files from server actions, scheduled jobs and agent tools, up to 25 MiB per call ([proxy helpers](https://docs.deep.space/sdk-reference/worker/proxy-helpers)); and `npx deepspace app files` for the owner to publish assets from the command line.

Not built in: a scope that shares a private file with a chosen group, such as a team, without making it public. The docs point to declaring a separate R2 bucket through [custom bindings](https://docs.deep.space/guides/custom-bindings), described there as a bucket with custom permissions; this page does not cover that.

Planned: agents creating their own DeepSpace account without a human sign-in. It is in testing on staging and is not enabled in production; see [Full-stack apps without a human in the loop](/agents/full-stack-apps-without-a-human-in-the-loop).

Building this for a business? See [deep.space/enterprise](https://deep.space/enterprise).
