---
title: "Keep storage clean"
description: "Release a file when your row lets go of it, give a file an end with storage.expire, let the component's sweep delete uploads nobody claimed or that failed their checks, and see how a person's files join their export and erasure."
canonical_url: "https://nuxt-backend.dev/docs/build/data/files/cleanup"
---
# Keep storage clean

> Release a file when your row lets go of it, give a file an end with storage.expire, let the component's sweep delete uploads nobody claimed or that failed their checks, and see how a person's files join their export and erasure.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

Files pile up quietly: a cover replaced, a strip deleted, an upload from a tab someone closed. Convex keeps every stored file until code deletes it, with no reference counting. The package keeps one owner record per file: release the file when your row lets go of it and both go together, while the `backend` component's maintenance deletes what nobody claimed, with no cron of yours.

## Release a file your row lets go of

Call `storage.release(ctx, storageId)` in the same mutation that drops the reference, so the row and the file go together:

```ts [backend/strips.ts]
import { backendError } from 'nuxt-backend/functions'
import { v } from 'convex/values'
import { workspace } from './functions'
import { storage } from './storage'

export const remove = workspace.mutation({
  args: { id: v.id('strips') },
  handler: async (ctx, { id }) => {
    const strip = await ctx.db.get('strips', id)
    if (strip?.workspaceId !== ctx.workspace.id) throw backendError('forbidden', { reason: 'other_workspace' })
    await storage.release(ctx, strip.photoId)
    await storage.release(ctx, strip.coverId)
    await storage.revokeShareLink(ctx, 'strips', id)
    await ctx.db.delete('strips', id)
  },
})
```

`release` takes a storage id, or `null` or `undefined` and does nothing. It deletes the owner record and the file, gives the bytes back to the quota, and calling it twice is safe. A row deleted in batches by a [retention rule](https://nuxt-backend.dev/docs/build/data/retention) releases its files in the rule's `onDelete`.

## Give a file an end

Some files go on a date rather than with a row: source photos a month after the comic printed, an export after a week. `storage.expire(ctx, storageId, at)` sets that date on the file's owner record, and the component's maintenance deletes the file within the hour after `at`, with its record, giving its bytes back to the quota. No table field, index, rule or cron of yours:

```ts [backend/strips.ts]
import { backendError } from 'nuxt-backend/functions'
import { DAY } from 'nuxt-backend/rate-limit'
import { v } from 'convex/values'
import { workspace } from './functions'
import { storage } from './storage'

export const publish = workspace.mutation({
  args: { id: v.id('strips') },
  handler: async (ctx, { id }) => {
    const strip = await ctx.db.get('strips', id)
    if (strip?.workspaceId !== ctx.workspace.id) throw backendError('forbidden', { reason: 'other_workspace' })
    await ctx.db.patch('strips', id, { status: 'ready' })
    // The source photo goes 30 days after the strip is published.
    await storage.expire(ctx, strip.photoId, Date.now() + 30 * DAY)
  },
})
```

`at` is epoch milliseconds or a `Date`; `null` keeps the file again. A time already past, the epoch or before included, is due at the next pass. `expire` returns whether the id names a kept file: `false` for no id, an unknown one, or an upload nobody claimed yet. Calling it again moves the date. Until the file goes it is served as before; afterwards your row reads `null` from `storage.fileUrl`, as after `release`. Like `release`, it checks no owner: pass an id read from your own row.

## Show it in a page

A delete that takes files with it deserves a confirmation that says so:

```vue [app/components/DeleteStrip.vue]
<script setup lang="ts">
import { api } from '#backend/api'

import type { Id } from '#backend/dataModel'

const props = defineProps<{ stripId: Id<'strips'>, title: string }>()
const remove = useMutation(api.strips.remove)
const dialog = ref<HTMLDialogElement>()
</script>

<template>
  <button type="button" @click="dialog?.showModal()">Delete strip</button>
  <dialog ref="dialog" aria-labelledby="delete-heading">
    <h2 id="delete-heading">Delete "{{ title }}"?</h2>
    <p>The strip, its photo and its cover are deleted, and its share link stops working.</p>
    <button type="button" @click="remove({ id: props.stripId }).then(() => dialog?.close())">Delete strip</button>
    <button type="button" @click="dialog?.close()">Cancel</button>
  </dialog>
</template>
```

## What the sweep deletes

<table>
<thead>
  <tr>
    <th>
      A file in storage
    </th>
    
    <th>
      What happens
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Claimed or stored, with an owner record
    </td>
    
    <td>
      Kept until <code>
        release
      </code>
      
      , or the owner's erasure
    </td>
  </tr>
  
  <tr>
    <td>
      Given an end with <code>
        storage.expire
      </code>
    </td>
    
    <td>
      Deleted by the first maintenance pass after its end
    </td>
  </tr>
  
  <tr>
    <td>
      Never claimed, under a day old
    </td>
    
    <td>
      Kept: the person may still be on the page that uploads it
    </td>
  </tr>
  
  <tr>
    <td>
      Never claimed, a day old or more
    </td>
    
    <td>
      Deleted by the next maintenance pass
    </td>
  </tr>
  
  <tr>
    <td>
      Claimed, then refused by its type check
    </td>
    
    <td>
      Deleted at once
    </td>
  </tr>
</tbody>
</table>

The sweep runs inside the `backend` component, where the files and their records live. It reads storage a page at a time and keeps its place between passes, so a large backlog never fills one transaction. A refused claim rolls its mutation back, so a rejected upload is an unclaimed one, and the sweep deletes it too. A file stored in one mutation is never an orphan.

DevTools shows the sweep's last pass and how many files it deleted on the [Overview tab](https://nuxt-backend.dev/docs/develop/devtools#overview), beside the component's other [maintenance tasks](https://nuxt-backend.dev/docs/build/data/jobs/scheduled#the-maintenance-the-component-runs).

## A person's files in export and erasure

- **Export.** A person's data export lists their files, each with its type, size and a link to its bytes: every file they own, and every file of a workspace that goes with their account, beside the share links they turned on. The files also come as zip parts, behind links that end with the export's own, and each file in the export names the part and the entry it is in. [Export and delete an account](https://nuxt-backend.dev/docs/build/auth/accounts/data) shows the export.
- **Erasure.** Deleting an account deletes the files it owns, and those of its personal workspace and of any workspace it was the only member of. Files of a shared workspace stay with the workspace.
- **Your rows.** A row of yours that points at a deleted file reads `null` from `getFileUrl` and `storage.fileUrl`. Clear the field in your account source if the row stays.

## What happens when…

<table>
<thead>
  <tr>
    <th>
      Situation
    </th>
    
    <th>
      Result
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        release
      </code>
      
       gets an id with no owner record
    </td>
    
    <td>
      Nothing: it returns without an error
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        expire
      </code>
      
       gets an id with no owner record
    </td>
    
    <td>
      Nothing: it returns <code>
        false
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        expire
      </code>
      
       gets an <code>
        at
      </code>
      
       that is no time, such as <code>
        NaN
      </code>
    </td>
    
    <td>
      A <code>
        TypeError
      </code>
      
      , and the mutation rolls back
    </td>
  </tr>
  
  <tr>
    <td>
      A row still points at a released file
    </td>
    
    <td>
      <code>
        getFileUrl
      </code>
      
       and <code>
        storage.fileUrl
      </code>
      
       return <code>
        null
      </code>
      
      , and <code>
        <StorageImage>
      </code>
      
       shows <code>
        missing
      </code>
    </td>
  </tr>
</tbody>
</table>

## Limits

- **release and expire check no owner.** Pass them an id read from your own row, never one from a client's arguments.
- **An end is kept to the hour.** Maintenance runs hourly, so a file goes up to an hour after its `at`. For a download that must stop at the minute, hand out an [expiring URL](https://nuxt-backend.dev/docs/build/data/files/images#serve-a-private-file-for-a-while).
- **Files stored outside setupStorage.** Files your app stored with `ctx.storage` directly live in the app's own storage, which the component cannot see: the sweep, export and erasure leave them alone. Keep deleting them with your own code, and send new uploads through `setupStorage`.
- **Cached copies.** An optimizer's resized copy can outlive the file until its cache expires ([Show images](https://nuxt-backend.dev/docs/build/data/files/images#limits)).

## Test it

```ts [backend/strips.test.ts]
import { readFile } from 'node:fs/promises'
import { asUser, defineBackendTestApp } from 'nuxt-backend/test'
import { expect, test } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('deleting a strip releases its photo', async () => {
  const author = await asUser(testApp())
  const id = await author.mutation(api.strips.create, { title: 'Monday' })
  const png = new Uint8Array(await readFile(new URL('./fixtures/panel.png', import.meta.url))).buffer
  await author.mutation(api.strips.addPhoto, { id, photo: png })
  const { photoId } = (await author.query(api.strips.get, { id }))!
  await author.mutation(api.strips.remove, { id })
  expect(await author.query(api.storage.getFileUrl, { storageId: photoId! })).toBeNull()
})
```

## Related

- [Accept checked uploads](https://nuxt-backend.dev/docs/build/data/files/checked-uploads): `store`, `claim` and the owner they record.
- [Delete old data on a schedule](https://nuxt-backend.dev/docs/build/data/retention): `onDelete` for rows a rule prunes, on a `schedule`.
- [Schedule jobs](https://nuxt-backend.dev/docs/build/data/jobs/scheduled#the-maintenance-the-component-runs): the component's maintenance.
- [Limits and retention](https://nuxt-backend.dev/docs/reference/backend/limits): how long the package keeps its own records.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
