typescript
41 lines · 7 steps
Streaming CSV file downloads in NestJS
A NestJS controller streams a report file to the client without buffering it in memory.
Explained by
highlit
1import { Controller, Get, Param, StreamableFile, Res, NotFoundException, Header } from '@nestjs/common';
2import { Response } from 'express';
3import { createReadStream, promises as fsp } from 'fs';
4import { join } from 'path';
5import { ReportsService } from './reports.service';
6
7@Controller('reports')
8export class ReportsController {
9 constructor(private readonly reportsService: ReportsService) {}
10
11 @Get(':id/export')
12 @Header('Content-Type', 'text/csv')
13 async export(
14 @Param('id') id: string,
15 @Res({ passthrough: true }) res: Response,
16 ): Promise<StreamableFile> {
17 const report = await this.reportsService.findExport(id);
18 if (!report) {
19 throw new NotFoundException(`Report ${id} not found`);
20 }
21
22 const filePath = join(this.reportsService.exportDir, report.fileName);
23
24 let stat;
25 try {
26 stat = await fsp.stat(filePath);
27 } catch {
28 throw new NotFoundException('Export file is no longer available');
29 }
30
31 res.set({
32 'Content-Length': stat.size.toString(),
33 'Content-Disposition': `attachment; filename="${report.fileName}"`,
34 });
35
36 const stream = createReadStream(filePath);
37 return new StreamableFile(stream, {
38 disposition: `attachment; filename="${report.fileName}"`,
39 });
40 }
41}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1StreamableFile lets you send large files as a stream instead of loading them fully into memory.
- 2Using passthrough:true keeps NestJS in control of the response while you still set custom headers manually.
- 3Validating both the database record and the file on disk avoids serving broken or missing downloads.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/streaming-csv-file-downloads-in-nestjs-explained-typescript-451d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.