Configuration
Every MediaModule option, the MediaService surface, and the injection tokens — in one place.
The complete configuration surface for @dudousxd/nestjs-media. The disks are configured with StorageModule from @nestjs/storage (its options); register it before MediaModule.
MediaModule.forRoot(options)
interface MediaModuleOptions {
// ── media-library — enabled when `store` is present ─────────────────
store?: MediaStore | { inject?: InjectionToken[]; useFactory: (...deps) => MediaStore };
collections?: MediaCollectionConfig[];
imageProcessor?: ImageProcessor;
// ── resumable uploads — enabled when `uploadSessions` is present ─────
uploadSessions?: UploadSessionStore | { inject?; useFactory };
uploadTmpPrefix?: string; // default '.uploads'
multipart?: Record<string, MultipartUploadDriver>; // side-car per StorageModule disk, e.g. { s3: s3Multipart(opts) }
tus?: { // mounts the tus HTTP controller
disk: string;
basePath?: string; // default '/media/uploads'
maxSize?: number; // reject larger creations (bytes)
keyFor?: (filename: string, token: string, metadata: Record<string, string>) => string;
};
// ── scope records and upload sessions by the request's tenant ────────
tenancy?:
| 'inherit'
| false
| {
enabled?: 'inherit' | boolean;
kinds?: string[];
family?: string;
required?: boolean;
nullRows?: 'tenantless' | 'shared';
pathPrefix?: boolean;
};
// ── who may read/attach/delete through MediaService ────────────────────
authorize?: (user: unknown, action: 'read' | 'attach' | 'delete', subject: MediaRecord | MediaAttachTarget) => void | Promise<void>;
// ── direct (presigned multipart) uploads — needs a `multipart` side-car ─
direct?: { // mounts the direct upload controller
disk: string;
basePath?: string;
partSize?: number; // default 8 MiB
};
// ── protecting and mounting the upload controllers ───────────────────
decorators?: ClassDecorator[]; // applied to every upload controller, e.g. Can(...)
routes?: boolean; // false → mount no upload controller
mount?: { tus?: boolean; multipart?: boolean; direct?: boolean }; // turn single surfaces off
imports?: DynamicModule['imports']; // modules providing DI deps for a decorator's guards
}| Option | Required | Purpose |
|---|---|---|
store | — | Enables media.library. An instance, or { inject, useFactory } (e.g. typeOrmMediaStore({ connectionName })) |
collections | — | Per-collection rules + conversions |
imageProcessor | — | Required only if any collection declares conversions |
uploadSessions | — | Enables media.uploads (the resumable engine) |
uploadTmpPrefix | — | Where in-progress chunks are staged on the disk (a valid key, default .uploads) |
multipart | — | Native multipart side-cars by disk name. A name that isn't a StorageModule disk fails at boot |
authorize | — | Checked by MediaService.serve()/url() (read), attach(), delete(); throw to refuse. See authorize |
tenancy | — | Default 'inherit': scope records and upload sessions by the request's tenant when ContextModule turns tenancy on. false opts out. See Tenancy |
tus | — | Mounts MediaUploadController (needs uploadSessions) |
direct | — | Enables media.directUploads + mounts MediaDirectUploadController (needs a multipart side-car for the disk) |
decorators | in production, unless nothing is mounted | Class decorators applied to every mounted upload controller, e.g. [UseGuards(AuthenticationGuard), Can(MediaPolicy, 'upload')]. The controllers are @Can.Anyone()-open to @nestjs/authorization's global guard either way. See Protecting the routes. |
routes | — | false mounts no upload controller; serve them from your own (see Mount it yourself). Providers work either way. Default true. |
mount | — | { tus?, multipart?, direct? } turns single surfaces off. Default: mount what's configured. |
imports | — | Modules providing DI deps for a guard passed through decorators |
Protecting the routes
The upload controllers have no auth of their own. Protect them with NestJS's first-party tools, one of two ways:
- Mount them yourself:
routes: false, then extend the exported controllers —@Can(MediaPolicy, 'upload') @Controller('media/uploads') class UploadsController extends MediaUploadController {}. decoratorson the mounted controllers —MediaModule.forRoot({ ..., decorators: [UseGuards(AuthenticationGuard), Can(MediaPolicy, 'upload')] }).
Production rule: when NODE_ENV === 'production', MediaModule.forRoot/forRootAsync throw at module definition if they mount upload routes with no decorators (an empty array counts as none), with an error naming both ways. Outside production undecorated routes mount open.
The /media console is different: it takes an authorize option on MediaDashboardModule and never refuses to boot. See the console's Access section.
MediaModule.forRootAsync(options)
Same options, resolved through a factory with DI — except decorators, routes and mount, which are static fields on the config object itself, not part of what useFactory resolves (controllers, and the enhancers bound to them, are wired at module-build time, before any async factory runs):
interface MediaModuleAsyncOptions {
imports?: any[];
inject?: any[];
useFactory: (...args: any[]) => MediaModuleOptions | Promise<MediaModuleOptions>; // stores as instances
store?: { inject?; useFactory }; // static — a store Nest builds (wins over the factory's)
uploadSessions?: { inject?; useFactory }; // static
decorators?: ClassDecorator[]; // static — see MediaModuleOptions.decorators
routes?: boolean; // static, default true
mount?: { tus?: boolean; multipart?: boolean; direct?: boolean }; // static, default all true
}Use this when options come from configuration (ConfigService) or authorize needs an injected service.
`mount` on forRootAsync
forRootAsync can't know at module-build time whether tus/direct will end up configured by useFactory, so by default it mounts all three controllers and each 501s if its feature is left unconfigured. Set the ones you never use to false in mount so they don't exist as dead, always-501 surface — e.g. mount: { direct: false } — or routes: false to mount none and serve them yourself. (forRoot takes the same mount, on top of only mounting what's configured.)
MediaCollectionConfig
interface MediaCollectionConfig {
name: string;
single?: boolean; // attaching replaces existing media
disk?: string; // override the target disk for this collection
acceptsMimeTypes?: string[]; // allow-list, else MimeNotAllowedError
conversions?: ConversionPreset[];
}
interface ConversionPreset {
name: string;
width?: number; height?: number;
fit?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside';
format?: 'jpeg' | 'png' | 'webp' | 'avif';
quality?: number;
eager?: boolean; // generate on attach instead of on first access
}MediaService
class MediaService {
serve(id, conversion?, { req, res, user?, ...serveFileOptions }): Promise<StreamableFile | undefined>;
url(id, conversion?, { user?, expiresIn?, filename?, disposition? }?): Promise<string>;
attach(input: AttachInput, { user? }?): Promise<MediaRecord>;
delete(id, { user? }?): Promise<void>;
get library(): MediaLibrary; // layer 2, unchecked — throws if no store configured
get attachments(): AttachmentManager; // attachment-as-column API — always available
get uploads(): ResumableUploadManager; // resumable proxy — throws if no uploadSessions configured
get directUploads(): DirectUploadManager; // direct multipart — throws if no direct configured
}Why the getters throw
library, uploads, and directUploads throw a clear, actionable error when their feature wasn't configured, rather than handing you undefined. The boundary is explicit: if you didn't pass a store, media.library tells you so by name.
MediaLibrary
attach(input: AttachInput): Promise<MediaRecord>;
ensureConversion(id: string, conversion: string): Promise<MediaRecord>;
list(ownerType: string, ownerId: string, collection?: string): Promise<MediaRecord[]>;
delete(id: string): Promise<void>;
url(id: string, conversion?: string, options?: StorageSignedUrlRequest): Promise<string>; // public, else signed
locate(id: string, conversion?: string): Promise<{ record; disk; path; fileName }>;
interface AttachInput {
ownerType: string; ownerId: string; collection: string;
fileName: string; mimeType: string; contents: Buffer | Readable;
size?: number; name?: string;
customProperties?: Record<string, unknown>;
disk?: string;
}Injection tokens
For advanced wiring, the module also exports tokens you can inject directly:
import { MEDIA_LIBRARY, MEDIA_ATTACHMENTS, MEDIA_UPLOADS, MEDIA_TUS, MEDIA_DIRECT, MEDIA_MULTIPART } from '@dudousxd/nestjs-media';| Token | Resolves to |
|---|---|
MEDIA_LIBRARY | MediaLibrary | null |
MEDIA_ATTACHMENTS | AttachmentManager |
MEDIA_UPLOADS | ResumableUploadManager | null |
MEDIA_TUS | TusUploadHandler | null |
MEDIA_DIRECT | DirectUploadManager | null |
MEDIA_STORE | MediaStore | null (Symbol.for) |
MEDIA_UPLOAD_SESSIONS | UploadSessionStore | null (Symbol.for) |
MEDIA_MULTIPART | Record<string, MultipartUploadDriver> (Symbol.for) |
The disks themselves are @nestjs/storage's Storage (or @InjectDisk(name)).
Error codes
| Error | code |
|---|---|
InvalidMediaKeyError (status 400) | MEDIA_INVALID_KEY |
UnsupportedOperationError | MEDIA_UNSUPPORTED_OP |
MimeNotAllowedError | MEDIA_MIME_NOT_ALLOWED |
MediaNotFoundError | MEDIA_RECORD_NOT_FOUND |
ConversionNotDefinedError | MEDIA_CONVERSION_NOT_DEFINED |
ImageProcessorMissingError | MEDIA_IMAGE_PROCESSOR_MISSING |
UploadSessionNotFoundError | MEDIA_UPLOAD_SESSION_NOT_FOUND |
UploadOffsetConflictError | MEDIA_UPLOAD_OFFSET_CONFLICT |
InvalidPartNumberError | MEDIA_INVALID_PART_NUMBER |
MediaTenancyUnavailableError | MEDIA_TENANCY_UNAVAILABLE |
Storage errors (StorageFileNotFoundError, StorageInvalidKeyError, …) are @nestjs/storage's; see Migrating.