Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To download files through Fastify in NestJS, follow the below steps:

  1. First, install Fastify and Fastify-static npm packages using the following command:
npm install fastify fastify-static
  1. After installing, import FastifyAdapter and fastifyStatic modules from Fastify in your NestJS AppModule:
import { Module } from '@nestjs/common';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import fastifyStatic from 'fastify-static';

@Module({
  imports: [],
})
export class AppModule {}
  1. In the AppModule, create an instance of FastifyAdapter and use its getInstance() method to get the underlying Fastify instance:
@Module({
  imports: [],
})
export class AppModule {
  async configure(app: NestFastifyApplication): Promise<void> {
    const fastifyAdapter = app.get(HttpAdapterHost)?.getInstance() as FastifyAdapter;

    // Define the static assets directory
    fastifyAdapter.register(fastifyStatic, {
      root: path.join(__dirname, '..', '..', 'public'),
    });
  }
}
  1. In your controller, create an endpoint that returns a file:
@Controller('files')
export class FilesController {
  @Get(':filename')
  async downloadFile(
    @Param('filename') filename: string,
  ): Promise<Observable<string>> {
    return of(filename);
  }
}
  1. In the downloadFile method of the controller, return a file stream using Fastify's reply.sendFile() method:
@Controller('files')
export class FilesController {
  @Get(':filename')
  async downloadFile(
    @Param('filename') filename: string,
    @Res() res: FastifyReply,
  ): Promise<void> {
    const filePath = path.join(__dirname, '..', '..', 'public', filename);

    res.type('application/octet-stream'); // Set the content type
    res.sendFile(filePath); // Send the file stream
  }
}
  1. Access the file by making a GET request to the endpoint, passing the filename as a parameter.

That's it! You've successfully downloaded a file through Fastify in NestJS.