---
title: "Files"
description: "Uploads and file storage with ablage, in the app's own bucket."
canonical_url: "https://docs.dev.lightdrop.cloud/guides/files"
---
# Files

> Uploads and file storage with ablage, in the app's own bucket.

Apps store files with [ablage](https://github.com/Niki2k1/ablage). On wervt every app gets its own
bucket in the stack's Garage (S3-compatible, self-hosted), and only that app can read or write it.
`@wervt/nuxt` connects ablage to it, so there's nothing to configure.

```bash
pnpm add ablage
```

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  modules: ['@wervt/nuxt', 'ablage'],
})
```

```ts [server/api/avatars.post.ts]
import { defineEventHandler } from 'nuxt/server'
import { readUploadedFile, useFileStorage } from '#imports'

export default defineEventHandler(async (event) => {
  const upload = await readUploadedFile(event, { types: ['image'], maxSize: '5MB' })
  return useFileStorage().put('avatars', upload.data, {
    contentType: upload.type,
    name: upload.name,
  })
})
```

```ts [server/api/avatars/[id].ts]
import { defineEventHandler } from 'nuxt/server'
import { sendStoredFile } from '#imports'

// Without a method suffix, so HEAD and Range requests reach it too.
export default defineEventHandler((event) =>
  sendStoredFile(event, { group: 'avatars', id: event.context.params!.id }),
)
```

`put`, `get`, `head`, `list`, `remove` and the rest of ablage's API work as documented there.
`nuxt dev` creates the app's bucket in the local stack's Garage. Needs ablage 0.1.1 or newer.

## Large files: straight to the bucket

Routes like the ones above pass the bytes through the app's isolate, which has 150 MB of memory
and 5 minutes per request, so keep them to a few tens of MB. For anything bigger, such as video,
let browsers talk to the bucket directly at `media.<domain>`:

- **Downloads:** `signedUrl()` returns a presigned link to the bucket, valid for `expiresIn`
seconds (up to 7 days). The bucket serves the bytes and `Range` requests.
- **Uploads:** three small routes start, finish and abort an upload, and `useDirectUpload()` sends
the file: in one `PUT`, or as a multipart upload in parallel parts for large files.

```ts [server/api/videos.get.ts]
import { defineEventHandler } from 'nuxt/server'
import { useFileStorage } from '#imports'

export default defineEventHandler(async () => {
  const storage = useFileStorage()
  const { objects } = await storage.list('videos', { limit: 50 })
  return Promise.all(
    objects.map(async (file) => ({
      name: file.name,
      url: await storage.signedUrl(file, { expiresIn: 3600 }),
    })),
  )
})
```

```ts [server/api/uploads/start.post.ts]
import { defineEventHandler, readBody } from 'nuxt/server'
import { useFileStorage } from '#imports'

export default defineEventHandler(async (event) => {
  const { name, type, size } = await readBody(event)
  // Check who may upload here; the size and type are checked before anything is signed.
  return useFileStorage().createUpload('videos', {
    name,
    contentType: type,
    size,
    maxSize: '2GB',
    types: ['video'],
  })
})
```

```ts [server/api/uploads/complete.post.ts]
import { defineEventHandler, readBody } from 'nuxt/server'
import { useFileStorage } from '#imports'

export default defineEventHandler(async (event) => {
  const { token, parts } = await readBody(event)
  return useFileStorage().completeUpload(token, { parts })
})
```

```ts [server/api/uploads/abort.post.ts]
import { defineEventHandler, readBody } from 'nuxt/server'
import { useFileStorage } from '#imports'

export default defineEventHandler(async (event) => {
  await useFileStorage().abortUpload((await readBody(event)).token)
  return null
})
```

```vue [app/pages/upload.vue]
<script setup lang="ts">
const uploads = useDirectUpload({
  start: '/api/uploads/start',
  complete: '/api/uploads/complete',
  abort: '/api/uploads/abort',
})
</script>

<template>
  <input type="file" @change="uploads.add([...($event.target as HTMLInputElement).files!])" />
  <p v-for="item in Object.values(uploads.items)" :key="item.file.name">
    {{ item.file.name }}: {{ item.progress.toFixed(0) }}% {{ item.error }}
  </p>
</template>
```

A file only shows up in `list()` once `completeUpload()` has checked its size. The bucket accepts
uploads from the app's own origin (CORS). Uploads that are never completed are removed after a
day: unfinished multipart uploads by the bucket itself, and files sent in one `PUT` but never
completed by the control plane, which checks every few hours. Until then they count against the
bucket quota.

## Images: resized on the way out

`imageUrl()` returns the URL of a resized or converted version of an image in the bucket. wervt's
image service ([imgproxy](https://imgproxy.net)) makes it on request, so the app stores one file
and never holds the pixels itself: the original can be a 40 MB photo.

```ts [server/api/photos.get.ts]
import { imageUrl } from '@wervt/nuxt/server'
import { defineEventHandler } from 'nuxt/server'
import { useFileStorage } from '#imports'

export default defineEventHandler(async () => {
  const { objects } = await useFileStorage().list('photos', { limit: 50 })
  return objects.map((file) => ({
    name: file.name,
    thumb: imageUrl(file, { width: 400, height: 400, fit: 'fill', gravity: 'smart' }),
    full: imageUrl(file, { width: 2048, quality: 85 }),
    download: imageUrl(file, { format: 'jpg', quality: 95, keepMetadata: true, download: file.name }),
  }))
})
```

```vue
<img :src="photo.thumb" width="400" height="400" loading="lazy" />
```

<table>
<thead>
  <tr>
    <th>
      Option
    </th>
    
    <th>
      What
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        width
      </code>
      
      , <code>
        height
      </code>
    </td>
    
    <td>
      Pixels. Leave one out to keep the aspect ratio.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        fit
      </code>
    </td>
    
    <td>
      <code>
        fit
      </code>
      
       (inside the box, the default), <code>
        fill
      </code>
      
       (cover it, cut off the rest) or <code>
        force
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        gravity
      </code>
    </td>
    
    <td>
      What <code>
        fill
      </code>
      
       and <code>
        crop
      </code>
      
       keep: <code>
        center
      </code>
      
      , <code>
        north
      </code>
      
      , …, <code>
        smart
      </code>
      
      , or a focus point <code>
        { x, y }
      </code>
      
       from 0 to 1.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        crop
      </code>
    </td>
    
    <td>
      <code>
        { width, height, gravity }
      </code>
      
      , cut out before resizing. Below 1 it's a share of the source.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        rotate
      </code>
    </td>
    
    <td>
      <code>
        90
      </code>
      
      , <code>
        180
      </code>
      
       or <code>
        270
      </code>
      
       degrees, on top of the EXIF orientation, which is always applied.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        format
      </code>
    </td>
    
    <td>
      <code>
        webp
      </code>
      
       (default), <code>
        jpg
      </code>
      
      , <code>
        png
      </code>
      
      , <code>
        avif
      </code>
      
      , <code>
        gif
      </code>
      
       or <code>
        bmp
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        quality
      </code>
      
      , <code>
        dpr
      </code>
      
      , <code>
        blur
      </code>
      
      , <code>
        enlarge
      </code>
    </td>
    
    <td>
      As in imgproxy.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        keepMetadata
      </code>
    </td>
    
    <td>
      Keep EXIF data (capture date, camera). Removed by default.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        download
      </code>
    </td>
    
    <td>
      Answer as a download; a string names the file.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        expiresIn
      </code>
    </td>
    
    <td>
      Seconds the URL works. Without it, forever.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        options
      </code>
    </td>
    
    <td>
      Other <a href="https://docs.imgproxy.net/usage/processing" rel="nofollow">
        imgproxy processing options
      </a>
      
      , as in its URLs.
    </td>
  </tr>
</tbody>
</table>

- The source is an ablage file (`{ group, id }`, like the ones `list()` and `put()` return) or a
key in the bucket. JPEG, PNG, WebP, AVIF, GIF, HEIC (iPhone photos), TIFF and BMP are read, up
to 120 megapixels.
- The URL is a path on the app's own host (`/_wervt/image/…`), signed by the app: nobody can ask
for other files or sizes. It carries no login of its own, though: whoever has the URL can load
that image (in a private app, after signing in). Create URLs in a route, after checking who
asks, and set `expiresIn` when access can be taken away again.
- A URL always names the same bytes, so browsers keep the image for a year, and so does a CDN in
front of a public app. After replacing a file, store it under a new id instead of the old one.
- Nothing is cached on the server: every request the browser or CDN doesn't answer resizes again.
Ask for a few fixed sizes rather than one per screen width.
- `nuxt dev` serves the same URLs through the local stack's imgproxy
(`docker compose up -d garage imgproxy`).

On the server, `fetchImage()` loads such a version instead of linking to it, with the same
options: to read pixels (a tiny `bmp` is trivial to parse), to send a smaller copy to another
service, or to store a converted file:

```ts
import { fetchImage } from '@wervt/nuxt/server'

// An iPhone's HEIC, kept as a JPEG every browser can show and download.
const res = await fetchImage(heic, { format: 'jpg', quality: 95, keepMetadata: true })
if (!res.ok) throw createError({ status: 422, message: 'Not an image' })
const jpeg = await useFileStorage().put('photos', new Uint8Array(await res.arrayBuffer()), {
  contentType: 'image/jpeg',
  name: 'photo.jpg',
})
```

The result passes through the isolate, so keep it to a few tens of MB.

## Not in isolates

ablage's tus uploads and its local image processing (sharp) don't work in isolates: tus stages
files on disk, and sharp is a native module. Use direct uploads instead of tus, and `imageUrl()`
instead of ablage's image transforms.

## Under the hood

- The bucket is `app-<name>`, with an S3 key that only works on it. Both are created on deploy.
The key is derived from `WERVT_DB_SECRET` like the database password, and passed to the app as
`WERVT_S3_*`.
- `wervt delete <app> --drop-database` also deletes the bucket, its files and unfinished uploads;
without the flag they're kept, like the database. The key stays, without access to anything, so
an app created again under the same name gets storage again. While the data is kept, only the
app's previous owner and members (and admins) can deploy that name again; dropping the data
frees it for everyone.
- Image URLs are checked by the runtime before the app is reached: it verifies the signature
(HMAC-SHA256 with `WERVT_IMAGE_KEY`, derived per app), makes a one-minute presigned link to the
app's own bucket and hands that to imgproxy. imgproxy has no credentials and only fetches from
Garage, so it can't be made to read anything else.
- Signed links and direct uploads go to `media.<domain>` (`WERVT_S3_PUBLIC_URL`), which serves the
bucket straight from the server, not through Cloudflare.
- Abandoned single-`PUT` uploads are found by ablage's `x-amz-meta-ablage-direct-upload` marker:
marked bytes (`<group>/data/<id>`) older than a day without their metadata object
(`<group>/meta/<id>`) are deleted. Files without the marker are never touched.
- Apps of accounts that aren't admins have a bucket quota (5 GB unless an admin changes it); past
it, uploads fail with `403 AccessDenied`. See [Limits](https://docs.dev.lightdrop.cloud/guides/private-apps#limits).
- The dashboard's **Storage** pages show each bucket's usage and browse, download and delete its
files; see [Dashboard](https://docs.dev.lightdrop.cloud/guides/dashboard).
- Files are backed up nightly; see [Backups](https://docs.dev.lightdrop.cloud/self-hosting/backups#files-garage).


## Sitemap

See the full [sitemap](https://docs.dev.lightdrop.cloud/sitemap.md) for all pages.
