Aviary
Concepts

The two layers

Storage (layer 1) is @nestjs/storage; the media-library (layer 2) attaches files to entities on top of its disks. How they relate, and where the seam is.

Two layers, and only the top one is nestjs-media. Understanding the seam between them is the key to using media well — and to knowing when you only need the bottom half.

Why split at all?

Plenty of file handling is not about entities. Writing a generated PDF to disk, caching a rendered image, letting the mail channel attach a buffer — these want a filesystem, nothing more. Meanwhile, "this user's avatar" or "this post's gallery with thumbnails" is genuinely a media library: files that belong to records, with rules and variants.

NestJS's own @nestjs/storage is the filesystem; media is the library. The seam is narrow: the media-library writes bytes through a @nestjs/storage disk and records metadata through a store. Everything else is independent.

Layer 1 — Storage (@nestjs/storage)

StorageModule.forRoot({ disks }) configures named disks (LocalDisk, S3Disk, InMemoryDisk, or your own StorageDisk); inject Storage (storage.disk(name)) or a disk with @InjectDisk(name). Writes, reads, ranges, listing, public and signed URLs, serveFile(), uploadToDisk(), typed errors and the key rule are all documented in File storage. media doesn't wrap any of it.

What media adds next to the disks, in -core:

  • Capabilities — diskCapabilities(disk, sidecar) computes { presign, multipart, publicUrls, list, ranged } for the dashboard, telescope and uploadMode: presign when signedUrl() works, publicUrls when url() works, multipart when a multipart side-car is configured for the disk.
  • Folders — StorageDisk.list() is flat. listFolderLevel(disk, prefix, page, sidecar) asks the side-car for one delimiter level (S3), or folds the flat listing with foldListing().
  • Keys — keySegment(text) turns untrusted text into one segment the disks accept; assertMediaKey(key) checks a whole key against the same rule.

Layer 2 — Media-library

MediaLibrary (exposed as media.library) attaches files to owning entities in named collections. It writes the bytes through a @nestjs/storage disk and persists a MediaRecord through a MediaStore.

const record = await media.library.attach({
  ownerType: 'Post',
  ownerId: '42',
  collection: 'gallery',
  fileName: 'photo.png',
  mimeType: 'image/png',
  contents: buffer,            // Buffer | Readable
  // optional: name, size, customProperties, disk (override)
});

await media.library.list('Post', '42', 'gallery'); // ordered MediaRecord[]
await media.library.list('Post', '42');             // all collections for the owner
await media.library.url(record.id);                  // public URL, else a signed one
await media.library.url(record.id, 'thumb');         // url to a conversion (lazily generated)
await media.library.locate(record.id, 'thumb');      // { record, disk, path, fileName }
await media.library.delete(record.id);               // removes record + bytes + every conversion

attach derives a deterministic storage path (ownerType/ownerId/collection/<id>/fileName, each segment through keySegment()), writes the bytes, takes the size from the write, computes the next order in the collection, and saves the record. delete removes the original and all generated conversion files (one delete([...]) per disk) before removing the row — no orphans.

url() returns the disk's public URL when it has a publicUrl, else a signed URL (signedUrl(), 15 minutes unless you pass { expiresIn }). To stream files through your app instead, with an authorization check, use MediaService.serve().

Binding an owner

Repeating ownerType/ownerId on every call gets old. media.library.for(type, id) binds them once — the table-model equivalent of spatie's HasMedia/InteractsWithMedia:

const post = media.library.for('Post', post.id); // id coerced to a string
await post.attach({ collection: 'gallery', fileName, mimeType, contents });
await post.list('gallery'); // ordered MediaRecord[]
await post.list();          // every collection for this post

url and delete act on a record id (not an owner), so they stay on media.library.

The MediaRecord

interface MediaRecord {
  id: string;
  ownerType: string; ownerId: string; collection: string;
  name: string; fileName: string; mimeType: string; size: number;
  disk: string; path: string; order: number;
  customProperties: Record<string, unknown>;
  conversions: Record<string, { path: string; disk: string }>;
  createdAt: Date; updatedAt: Date;
}

Collections

Collections are declared at module registration and control behavior:

collections: [
  // single-file: attaching replaces the previous file (record + bytes)
  { name: 'avatar', single: true, acceptsMimeTypes: ['image/png', 'image/jpeg'] },
  // multi-file with a target disk override and conversions
  { name: 'gallery', disk: 's3', conversions: [{ name: 'thumb', width: 200 }] },
]
OptionEffect
singleAttaching replaces any existing media in the collection (old record + bytes are deleted first)
diskTarget disk for this collection (else StorageModule's default disk)
acceptsMimeTypesAllow-list; other types are rejected with MimeNotAllowedError before any bytes are written
conversionsImage presets available for this collection (see Conversions)

An unregistered collection name is permitted with default behavior (multi-file, default disk, no conversions) — so you can attach to ad-hoc collections without declaring every one up front, and declare only the ones that need rules.

The media table is polymorphic and managed by your chosen ORM store — TypeORM, MikroORM, Drizzle, or Prisma, all behind the same MediaStore contract.

On this page