res.write() is not streaming data when node app deployed on AWS

I have a Nest.js (Node.js) application that uploads files to AWS S3. During the upload, I’m using a callback function to track and send live progress updates to the client. Here’s the code for the file upload:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export async function uploadFileAWS(key: string, file, progressCallback: (number) => void) {
const upload = new Upload({
client: s3Client,
params: {
Bucket: process.env.AWS_S3_BUCKET_NAME,
Key: key,
Body: file.buffer,
ContentType: file.mimetype,
},
leavePartsOnError: false,
});
upload.on('httpUploadProgress', (progress) => {
const percentage = Math.round((progress.loaded / progress.total) * 100);
progressCallback(percentage);
});
await upload.done();
}
</code>
<code>export async function uploadFileAWS(key: string, file, progressCallback: (number) => void) { const upload = new Upload({ client: s3Client, params: { Bucket: process.env.AWS_S3_BUCKET_NAME, Key: key, Body: file.buffer, ContentType: file.mimetype, }, leavePartsOnError: false, }); upload.on('httpUploadProgress', (progress) => { const percentage = Math.round((progress.loaded / progress.total) * 100); progressCallback(percentage); }); await upload.done(); } </code>
export async function uploadFileAWS(key: string, file, progressCallback: (number) => void) {
    const upload = new Upload({
        client: s3Client,
        params: {
            Bucket: process.env.AWS_S3_BUCKET_NAME,
            Key: key,
            Body: file.buffer,
            ContentType: file.mimetype,
        },
        leavePartsOnError: false,
    });

    upload.on('httpUploadProgress', (progress) => {
        const percentage = Math.round((progress.loaded / progress.total) * 100);
        progressCallback(percentage);
    });

    await upload.done();
}

Locally, everything works fine. When testing with Postman and my frontend client, they receive the response in a live stream format, and the progress of the file upload can be tracked in real-time.

However, after deploying the NestJS application to an AWS EC2 machine, the progress updates stop working as expected. The file is uploaded successfully, but the client only receives all the responses at the end, instead of progressively during the upload.

In the controller handling the request, I’m setting the headers for Server-Sent Events (SSE) like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>async uploadFile(@Body('type') type: FileType, @UploadedFile() file, @Res() res) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Connection', 'keep-alive');
res.setHeader('Cache-Control', 'no-cache');
try {
const key = await this.fileUploadService.uploadFile(type, file, (progress: number) => {
res.write(
`data: {"msg":"File Uploading in progress","data":{"progress":${progress}},"success":"true"}nn`
);
res.flush();
});
const url = `https://${process.env.AWS_S3_BUCKET_NAME}.s3.amazonaws.com/${key}`;
res.write(
`data: {"msg":"File Uploaded Successfully", "data":{"key": "${key}", "url": "${url}"},"success":"true"}nn`
);
} catch (error) {
console.error(error);
res.write(`data: {"msg":"Error uploading file","success":"false"}nn`);
} finally {
res.end();
}
}
</code>
<code>async uploadFile(@Body('type') type: FileType, @UploadedFile() file, @Res() res) { res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Connection', 'keep-alive'); res.setHeader('Cache-Control', 'no-cache'); try { const key = await this.fileUploadService.uploadFile(type, file, (progress: number) => { res.write( `data: {"msg":"File Uploading in progress","data":{"progress":${progress}},"success":"true"}nn` ); res.flush(); }); const url = `https://${process.env.AWS_S3_BUCKET_NAME}.s3.amazonaws.com/${key}`; res.write( `data: {"msg":"File Uploaded Successfully", "data":{"key": "${key}", "url": "${url}"},"success":"true"}nn` ); } catch (error) { console.error(error); res.write(`data: {"msg":"Error uploading file","success":"false"}nn`); } finally { res.end(); } } </code>
async uploadFile(@Body('type') type: FileType, @UploadedFile() file, @Res() res) {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('Cache-Control', 'no-cache');

    try {
        const key = await this.fileUploadService.uploadFile(type, file, (progress: number) => {
            res.write(
                `data: {"msg":"File Uploading in progress","data":{"progress":${progress}},"success":"true"}nn`
            );
            res.flush();
        });

        const url = `https://${process.env.AWS_S3_BUCKET_NAME}.s3.amazonaws.com/${key}`;
        res.write(
            `data: {"msg":"File Uploaded Successfully", "data":{"key": "${key}", "url": "${url}"},"success":"true"}nn`
        );
    } catch (error) {
        console.error(error);
        res.write(`data: {"msg":"Error uploading file","success":"false"}nn`);
    } finally {
        res.end();
    }
}

I’m not sure why this is happening after deployment. Could there be something specific to AWS EC2 or the network configuration that is causing the responses to be buffered and sent all at once instead of in real-time?

Any guidance or suggestions to resolve this issue would be greatly appreciated.

Initially, I suspected that the issue was caused by the NGINX proxy I was using. However, even after temporarily removing the NGINX proxy, the issue persists.

New contributor

Muhammad Younus Raza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật