# Add a field to an existing app without losing data

Add or reorganize fields in a DeepSpace app you built earlier without losing records: what the automatic schema migration handles, how to copy values into a new field, and how to verify or roll back the release.

Yes. On a DeepSpace app, adding a field is a schema edit and a redeploy. Existing records stay where they are: deploys don't wipe app data, and the SDK adds new columns and new collections on its own when the app's Durable Object starts after the deploy. What the SDK does not do is rename a field, change a field's type, remove a field, or fill old records with new values. "Reorganizing the fields" is therefore done in additive steps: add the new field, copy values into it, switch the app to read it, and leave the old column in place.

**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

- Which information do they want to add, split, merge or rename? An example with real values helps ("'Contact' should become 'First name' and 'Last name'").
- Should existing entries get a value for the new field, and what? Blank, a fixed value, or copied from another field?
- Is any field they want gone still useful for old entries? It can be hidden in the app without deleting the stored values.
- Who uses the app right now, and is there a quiet time for the update?

## What changes are safe

| Change                        | Handled automatically                      | What existing records see                                            |
| ----------------------------- | ------------------------------------------ | -------------------------------------------------------------------- |
| Add a field                   | Yes, `ALTER TABLE ADD COLUMN` after deploy | The field is empty until something writes it                         |
| Add a collection              | Yes, the table is created after deploy     | Nothing; it starts empty                                             |
| Rename a field                | No                                         | Treat it as add new + copy + keep old                                |
| Change a field's type         | No                                         | Add a new field of the new type and copy converted values            |
| Remove a field                | No                                         | Stop showing it; keep it in the schema so the stored values stay put |
| Fill old records with a value | No                                         | Run a one-time copy (step 4)                                         |

`default` and `required` apply when a record is created, not to records that already exist. A new `required: true` field does not fail on old rows, but old rows still have no value until they are updated.

## Steps

### 1. Get the app's current source

Work from the app's existing source, not a fresh scaffold; a new starter has a new app id and an empty database. If the source is not in the current environment, sign in with the account that owns the app (or a collaborator on it) and clone it. Confirm with your user before signing in on their behalf.

```bash
npx deepspace auth login
npx deepspace app list
npx deepspace clone <app-name-or-id>
cd <app-name>
npx deepspace releases
```

`releases` lists what is live now. Note the current release id; it is the rollback target in step 6.

### 2. Add the new field to the schema

Add columns, don't edit or delete the existing ones. Example: a `contacts` collection with a single `name` field gains `firstName` and `lastName`.

```ts
// src/schemas/contacts-schema.ts
columns: [
  { name: 'name', storage: 'text', interpretation: 'plain' },        // existing, kept
  { name: 'phone', storage: 'text', interpretation: 'plain' },       // existing, kept
  { name: 'firstName', storage: 'text', interpretation: 'plain' },   // new
  { name: 'lastName', storage: 'text', interpretation: 'plain' },    // new
],
```

If the collection has a `writableFields` list for a role, add the new fields there too, or writes that include them are refused.

### 3. Make the app read old and new records

Until every record has the new fields, the UI reads the new field and falls back to the old one:

```tsx
const first = r.data.firstName ?? r.data.name?.split(" ")[0] ?? "";
const last =
  r.data.lastName ?? r.data.name?.split(" ").slice(1).join(" ") ?? "";
```

Forms write the new fields from now on. Writing the old `name` as well keeps older parts of the app working during the change.

### 4. Copy values into the new field once

A server action runs as the app and can update every record. Restrict it to admins, because any signed-in user can call an action.

```ts
// src/actions/index.ts
import type { ActionHandler } from "deepspace/worker";

export const actions: Record<string, ActionHandler<Env>> = {
  splitContactNames: async ({ userId, tools, env }) => {
    // The owner is admin; other admins carry role 'admin' on their users row.
    const me = await tools.get("users", userId);
    const isAdmin =
      userId === env.OWNER_USER_ID ||
      (me.success && me.data.record.data.role === "admin");
    if (!isAdmin) return { success: false, error: "Admins only" };
    const res = await tools.query("contacts", { limit: 500 });
    if (!res.success) return res;
    let updated = 0;
    for (const r of res.data.records) {
      if (r.data.firstName || !r.data.name) continue;
      const [firstName, ...rest] = String(r.data.name).split(" ");
      await tools.update("contacts", r.recordId, {
        firstName,
        lastName: rest.join(" "),
      });
      updated++;
    }
    return { success: true, data: { updated, seen: res.data.records.length } };
  },
};
```

The action skips records that already have `firstName`, so running it twice changes nothing the second time. Call it again while `seen` equals the limit. It is exposed at `POST /api/actions/splitContactNames`; call it from an admin-only button in the app:

```ts
import { getAuthToken } from "deepspace";

const res = await fetch("/api/actions/splitContactNames", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${await getAuthToken()}`,
  },
  body: "{}",
});
console.log(await res.json()); // { success: true, data: { updated: 42, seen: 42 } }
```

### 5. Deploy and check

```bash
git add -A && git commit -m "Add firstName and lastName to contacts"
npx deepspace deploy --json
npx deepspace logs --since 15m --json
```

Then, in the live app: open an old record and check its values are all there, create a new record with the new fields, reload, run the copy once as an admin, and spot-check a few old records. The worker console prints `[schema-lint]` lines at boot if a schema declaration doesn't do what it looks like; fix those before handing the app over.

### 6. If the release is wrong

```bash
npx deepspace releases --json
npx deepspace rollback <previous-release-id> --yes --json
```

Rollback re-ships the earlier bundle; it does not delete records, and values written into the new fields stay stored. Rollback refuses when the earlier release declares fewer Durable Object classes, because finishing it would delete their data. The `--allow-do-deletion` flag overrides that and permanently deletes data. Confirm with your user, naming exactly what would be lost, before using it.

## Common failures and fixes

| Symptom                                     | Cause                                                               | Fix                                                                                       |
| ------------------------------------------- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| The app opens with no data                  | It was rebuilt from a fresh scaffold, which is a different app      | Clone the existing app (step 1) and deploy from that source                               |
| Old records show blanks in the new field    | Nothing has written the new field on old rows yet                   | Fall back to the old field (step 3) and run the copy (step 4)                             |
| Writes with the new field are refused       | The role's `writableFields` doesn't list it                         | Add the field to `writableFields` and redeploy                                            |
| A value seems gone after a "rename"         | The UI reads the new name, but the data is still under the old name | Read with a fallback, then copy the values over                                           |
| The copy action returns `Admins only`       | The caller isn't an admin                                           | Run it signed in as the app owner, who is always admin                                    |
| Deploy refused with `dirty_worktree`        | Uncommitted changes                                                 | Commit, then deploy                                                                       |
| `Not the app owner or a collaborator` (403) | The signed-in account can't deploy this app                         | Sign in as the owner, or have the owner run `npx deepspace app collaborators add <email>` |

## What to tell the person when it is live

- The new field is live at the same link, and every existing entry is still there.
- Old entries were filled in from the old field where that was possible; list any that couldn't be.
- The old field is hidden, not deleted, so nothing is lost if they change their mind.
- The previous version can be put back with one command if something looks wrong.

## Available today and planned

Available today, in the published SDK: automatic additive migrations for new fields and collections, server actions for one-time copies, `deepspace clone` and `deepspace releases`, and `deepspace rollback` that re-ships an earlier release without deleting records. Renames, type changes, removals and backfills are the app's own steps, as above.

Planned: agents creating their own DeepSpace account to return to an app without a human sign-in. It is in testing on staging and is not enabled in production; see [Permanent websites for AI agents](/agents/permanent-websites-for-ai-agents).

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