---
title: bucket
description: Declare a bucket of files in a luna, and store, read, list and sign URLs for them with ctx.blobs.
related:
  - /files-and-code/store-files
  - /files-and-code/upload-from-an-app
  - /sdk/t
---

`bucket` declares a bucket of objects, files with a content type and metadata, under the luna type's `blobs` option. A handler uses it as `ctx.blobs.<name>`.

```ts luna/lunas/profile.ts
import { bucket, defineLuna, t } from "luna";

export const Profile = defineLuna({
  name: "Profile",
  key: { id: t.string() },
  blobs: {
    files: bucket({ path: "files/{name...}" }),
  },
  handlers: (h) => ({
    save: h({ args: { name: t.string(), text: t.string() } }, async (ctx, { name, text }) => {
      await ctx.blobs.files.put(`files/${name}`, text);
    }),
    read: h({ args: { name: t.string() } }, (ctx, { name }) => ctx.blobs.files.text(`files/${name}`)),
  }),
});
```

## Reference

### bucket(spec)

| Prop | Type | Default | Description |
| - | - | - | - |
| `path` | `string` | - | Where objects go: segments split by `/`, where `{name}` stands for one segment and a last `{name...}` for the rest. |
| `types?` | `string[]` | - | The content types allowed, such as `"image/png"` or `"image/*"`, and with none, any type. |
| `maxSize?` | `number` | `10 GiB` | The largest object in bytes, at most 10 GiB. |
| `meta?` | `Ty<M>` | - | Each object's metadata type, built with `t`. |
| `public?` | `boolean` | `false` | Anyone may read objects at a plain URL, and otherwise only through a signed one. |
| `onUpload?` | `(ctx, object: BlobObject<M>) => void` | - | Runs when an upload through a signed URL finishes, and throwing rejects the upload. |

### Bucket

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The bucket's name. |
| `put(path, data, opts?)` | `Promise<BlobObject<M>>` | - | Stores an object of up to 256 MiB at `path`, replacing what is there, with `opts.contentType` and `opts.meta`. |
| `get(path, opts?)` | `Promise<{ object: BlobObject<M>; bytes: Uint8Array } \| null>` | - | The object and its bytes, or `null`, with `opts.range` as `[from, to)` in bytes. |
| `text(path)` | `Promise<string \| null>` | - | The object's bytes as UTF-8 text, or `null`. |
| `head(path)` | `BlobObject<M> \| null` | - | The object without its bytes, or `null`. |
| `list(opts?)` | `{ objects: BlobObject<M>[]; cursor: string \| null }` | - | Objects whose path starts with `prefix`, in path order, `limit` at a time, 100 by default and 1,000 at most. |
| `delete(path)` | `boolean` | - | Deletes the object, and returns `false` if there was none. |
| `copy(path, to)` | `BlobObject \| null` | - | Copies the object to a `BlobDestination`, or returns `null` if there was none. |
| `move(path, to)` | `BlobObject \| null` | - | Moves the object to a `BlobDestination`, or returns `null` if there was none. |
| `signUpload(path, opts?)` | `SignedUrl` | - | A URL an app uploads `path` to with `PUT`, limited by `opts.maxSize` and `opts.contentType`. |
| `signDownload(path, opts?)` | `SignedUrl` | - | A URL an app downloads `path` from with `GET`. |

`data` is a `Uint8Array` or a string. A string is stored as `text/plain; charset=utf-8` and bytes as `application/octet-stream`, unless you pass `contentType`. `opts.expiresIn` of both sign methods is in milliseconds, one hour by default.

### BlobObject

| Prop | Type | Default | Description |
| - | - | - | - |
| `bucket` | `string` | - | The bucket it is in. |
| `path` | `string` | - | Its path. |
| `hash` | `string` | - | Its ETag, which changes whenever the bytes do. |
| `size` | `number` | - | Its size in bytes. |
| `contentType` | `string` | - | Its content type. |
| `meta` | `M \| null` | - | Its metadata. |
| `created` | `number` | - | When it was made, in milliseconds since the epoch. |
| `updated` | `number` | - | When it last changed, in milliseconds since the epoch. |

### SignedUrl

| Prop | Type | Default | Description |
| - | - | - | - |
| `url` | `string` | - | A path and query, to add to your app's URL. |
| `method` | `"PUT" \| "GET"` | - | The method to send. |
| `expires` | `number` | - | When it stops working, in milliseconds since the epoch. |

### BlobDestination

A path in the same bucket as a `string`, or `{ bucket, path }` for another bucket of the same luna.

## Good to know

- An object written by a handler is there once the handler commits. A handler that fails leaves no object behind.
- An object's path must match its bucket's `path`, its type must be one of `types`, and its size at most `maxSize`. Otherwise the write fails.
- `put` and `get` handle at most 256 MiB at once. Read a larger object in parts with `range`, and upload one through `signUpload`.
- `onUpload` runs in one transaction with the object it commits. It must be synchronous, since writes cannot span an `await`. Start slower work with `ctx.send`.
- A signed URL is its own credential. Downloads through it, or from a public bucket, do not wake the luna.
- A public bucket's object is read at the same path as its signed download URL, without the query.
- Rows that reference an object with `t.blobRef` follow their `onDelete` when it is deleted. By default the delete fails. A move inside the bucket takes those references with it.

## Examples

### Read part of a large object

```ts luna/lunas/profile.ts
head: h({ args: { name: t.string() } }, async (ctx, { name }) => {
  const got = await ctx.blobs.files.get(`files/${name}`, { range: [0, 1024] });
  return got ? { type: got.object.contentType, first: got.bytes.length } : null;
}),
```

### Let an app upload a photo

```ts luna/lunas/profile.ts
import { bucket, defineLuna, t, table } from "luna";

export const Profile = defineLuna({
  name: "Profile",
  key: { id: t.string() },
  schema: { uploads: table({ id: t.id(), path: t.string(), size: t.int() }) },
  blobs: {
    photos: bucket({
      path: "photos/{photo}",
      types: ["image/*"],
      maxSize: 20 * 1024 * 1024,
      meta: t.object({ caption: t.string() }),
      onUpload: (ctx, object) => {
        ctx.db.uploads.insert({ path: object.path, size: object.size });
      },
    }),
  },
  handlers: (h) => ({
    uploadUrl: h({ args: { photo: t.string() } }, (ctx, { photo }) =>
      ctx.blobs.photos.signUpload(`photos/${photo}`, { expiresIn: 600_000, contentType: "image/png" }),
    ),
  }),
});
```

The app sends the file's bytes with `PUT` to `LUNA_URL` followed by `url`.

### Serve avatars to anyone

```ts luna/lunas/profile.ts
blobs: {
  avatars: bucket({ path: "avatar", types: ["image/png", "image/jpeg"], public: true }),
},
```

### Delete empty objects a page at a time

```ts luna/lunas/profile.ts
tidy: h({}, (ctx) => {
  let page = ctx.blobs.files.list({ prefix: "files/", limit: 100 });
  for (;;) {
    for (const o of page.objects) if (o.size === 0) ctx.blobs.files.delete(o.path);
    if (!page.cursor) break;
    page = ctx.blobs.files.list({ prefix: "files/", cursor: page.cursor, limit: 100 });
  }
}),
```

### Copy a photo to another bucket

```ts luna/lunas/profile.ts
useAsAvatar: h({ args: { photo: t.string() } }, (ctx, { photo }) => {
  ctx.blobs.photos.copy(`photos/${photo}`, { bucket: "avatars", path: "avatar" });
}),
```

A copy moves no bytes.
