Getting Started
Install nestjs-media on top of @nestjs/storage, wire MediaModule with a store, attach your first file, and serve it back — in about five minutes.
By the end of this page you'll have a working upload endpoint that stores a file on a disk, records it against an entity, and serves a thumbnail back.
Install
nestjs-media stores files on the disks of NestJS's first-party @nestjs/storage (LocalDisk, S3Disk, InMemoryDisk, or your own StorageDisk). Install it next to the umbrella package, plus the store and image engine you want. Everything is à la carte.
pnpm add @nestjs/storage @dudousxd/nestjs-media \
@dudousxd/nestjs-media-database-typeorm @dudousxd/nestjs-media-image-sharp@nestjs/storage needs Nest 12.1 or later. The umbrella package (@dudousxd/nestjs-media) carries the NestJS module and the core SPIs. Each ORM store and image engine is its own package, so you never pull sharp into a service that doesn't resize. Add @dudousxd/nestjs-media-disk-s3 only for resumable/direct uploads with native S3 multipart (see Uploads).
Register the module
Register the disks with StorageModule (its docs), then MediaModule on top: a store gives you the media-library layer; an imageProcessor and collections with conversions give you image variants.
import { Module } from '@nestjs/common';
import { LocalDisk, S3Disk, StorageModule } from '@nestjs/storage';
import { TypeOrmModule } from '@nestjs/typeorm';
import { MediaModule } from '@dudousxd/nestjs-media';
import { typeOrmMediaStore } from '@dudousxd/nestjs-media-database-typeorm/nest';
import { SharpImageProcessor } from '@dudousxd/nestjs-media-image-sharp';
@Module({
imports: [
TypeOrmModule.forRoot({ /* ... */ }),
StorageModule.forRoot({
default: 's3',
disks: {
s3: new S3Disk({ bucket: 'app-uploads', region: 'eu-west-1' }),
local: new LocalDisk({ root: './storage' }),
},
}),
MediaModule.forRoot({
// No upload routes in this app. Mounting them? Protect them: see "Protecting the routes"
// in the nestjs package docs.
routes: false,
// Nest injects the TypeORM DataSource (the default connection; `connectionName` for another).
store: typeOrmMediaStore(),
imageProcessor: new SharpImageProcessor(),
collections: [
{ name: 'avatar', single: true, acceptsMimeTypes: ['image/png', 'image/jpeg'] },
{
name: 'gallery',
conversions: [
{ name: 'thumb', width: 200 },
{ name: 'og', width: 1200, height: 630, eager: true },
],
},
],
}),
],
})
export class AppModule {}MediaModule is @Global() — import it once and inject MediaService anywhere. StorageModule is global by default too; MediaModule fails at boot, naming it, when it isn't registered. Use MediaModule.forRootAsync when the options come from configuration.
The TypeOrmMediaStore creates the media table on first use by default (non-destructive — see Persistence). Nothing else to migrate to get started.
Accept an upload
Wire a normal NestJS controller. Here with Multer's memory storage, so the file arrives as a Buffer:
import { Controller, Param, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { MediaService } from '@dudousxd/nestjs-media';
@Controller('posts/:id/photos')
export class PhotosController {
constructor(private readonly media: MediaService) {}
@Post()
@UseInterceptors(FileInterceptor('file'))
upload(@Param('id') postId: string, @UploadedFile() file: Express.Multer.File) {
return this.media.library.attach({
ownerType: 'Post',
ownerId: postId,
collection: 'gallery',
fileName: file.originalname,
mimeType: file.mimetype,
contents: file.buffer,
});
}
}attach writes the bytes to the collection's disk (the default one here), records a MediaRecord, and (because og is eager) generates that variant right away. It returns the saved record, including its id. The client's file name becomes one safe key segment (/, \, .. and control characters are replaced), since @nestjs/storage refuses such keys.
To stream uploads straight onto a disk instead of buffering them, use @nestjs/storage's uploadToDisk() storage engine and attach the stored key; nestjs-media doesn't wrap it.
Serve it back
Ask the library for a URL: the disk's public URL when it has a publicUrl, else a signed one (signedUrl(), 15 minutes by default). Conversions are generated lazily the first time you request them, then cached:
@Injectable()
export class PhotosService {
constructor(private readonly media: MediaService) {}
async list(postId: string) {
const media = await this.media.library.list('Post', postId, 'gallery');
return Promise.all(
media.map(async (m) => ({
id: m.id,
full: await this.media.library.url(m.id),
thumb: await this.media.library.url(m.id, 'thumb'), // generated + cached on first call
})),
);
}
}Or stream it through your app with MediaService.serve(), which answers Range, If-None-Match and the security headers via @nestjs/storage's serveFile():
@Get('media/:id')
file(@Param('id') id: string, @Req() req: Request, @Res({ passthrough: true }) res: Response) {
return this.media.serve(id, undefined, { req, res });
}For files that aren't media records, use the disk directly: Storage/@InjectDisk() from @nestjs/storage (docs).
Troubleshooting
`MediaLibrary is not configured`
You called media.library without passing a store to MediaModule. Add a store to enable the media-library layer; for plain files, use the @nestjs/storage disks directly.
`MediaModule stores files on the disks of @nestjs/storage`
StorageModule.forRoot({ disks }) isn't registered (or isn't global). Register it before MediaModule.
`url()` throws on the local disk
A LocalDisk has neither a public nor a signed URL until you give it publicUrl or signedUrls (then serve them with serveSignedUrl()). Or stream the file through your app with MediaService.serve().
Next steps
- Concepts → The two layers — the model in depth
- Concepts → Uploads & multipart — resumable tus + presigned direct
- Concepts → Conversions — lazy vs eager image variants
- Recipes — avatars, galleries, direct-to-S3, serving files
- Migrating to 0.x on @nestjs/storage — from
StorageManagerand the old drivers - Reference → Configuration — every
MediaModuleoption
Media
The media library for NestJS, on top of @nestjs/storage — the spatie feel for files. Entity attachments, image conversions, resumable and direct uploads, and a /media console, all wired into the ecosystem's diagnostics, codegen, and React glue points.
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.