Aviary
Recipes

Serving files

Public URLs, signed URLs, and streaming media records through your own controller with MediaService.serve().

Three ways to get a media record's bytes back to a client. For files that aren't media records, @nestjs/storage does the same things directly (url(), signedUrl(), serveFile(); docs).

url(): public, else signed

const src = await media.library.url(mediaId);           // original
const thumb = await media.library.url(mediaId, 'thumb'); // a conversion (generated on first use)

When the record's disk has a publicUrl (a CDN, a public bucket), you get that stable address. Otherwise you get a signed, expiring one (signedUrl(), 15 minutes by default):

await media.library.url(mediaId, undefined, { expiresIn: '5m', filename: 'invoice.pdf' });

S3Disk presigns on its own. A LocalDisk signs only with signedUrls: { baseUrl, keys }, and then your app serves those URLs with serveSignedUrl() (docs). A disk with neither throws: serve its files through a controller (below).

Streaming through a controller: MediaService.serve()

When you need an authorization check, or the disk can't hand out URLs, stream the record through Nest:

files.controller.ts
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
import type { Request, Response } from 'express';
import { MediaService } from '@dudousxd/nestjs-media';

@Controller('media')
export class FilesController {
  constructor(private readonly media: MediaService) {}

  @Get(':id/:conversion?')
  file(
    @Param('id') id: string,
    @Param('conversion') conversion: string | undefined,
    @Req() req: Request,
    @Res({ passthrough: true }) res: Response,
  ) {
    return this.media.serve(id, conversion, { req, res });
  }
}

serve() finds the record (404 for an unknown id), runs the module's authorize hook with 'read' and req.user (or the user you pass), generates the conversion if needed, and answers through @nestjs/storage's serveFile(): a single Range gets a 206, If-None-Match a 304, ETag/Last-Modified/Cache-Control (private unless the file has its own) and X-Content-Type-Options: nosniff are set. Content-Disposition is inline with the record's file name, but only for types that can't run script in your origin (images other than SVG, PDF, audio, video, plain text); anything else downloads. Pass disposition, filename or cacheControl to override.

The body streams: nothing is loaded into memory, and a client that disconnects releases the file or the S3 connection.

On this page