How to Add Antivirus and Malware Scanning to Your Next.js File Upload API
Accepting file uploads from users is a common requirement in modern web applications. However, allowing unscanned files into your system poses serious security risks. Malicious users can upload viruses, trojans, ransomware, and other malware that could compromise your infrastructure or infect other users.

In this guide, we’ll show you how to integrate antivirus scanning directly into your Next.js API routes using the attachmentAV API, creating a secure middleware solution for file uploads.
The Problem: Unsecured File Uploads
When users upload files to your application, you cannot trust the content. Even seemingly harmless files can contain:
- Viruses and malware that can infect your servers
- Trojans disguised as legitimate documents
- Malicious scripts embedded in PDFs or office documents
- Ransomware that could encrypt your data
Companies handling user-generated content need a reliable malware scanning solution before processing or storing these files.
The Solution: Real-Time Virus Scanning with Next.js API Routes
By integrating an antivirus API directly into your Next.js backend, you can scan files synchronously before they enter your system. This approach acts as middleware, intercepting uploads and verifying they’re clean before proceeding.
Architecture Overview
The solution works in three simple steps:
- User uploads a file to your Next.js API route
- Your API forwards the file to attachmentAV’s malware scanning service
- If clean, the file is processed; if infected, it’s rejected immediately
Implementation: Building a Secure File Upload Endpoint
Let’s walk through implementing a secure file upload endpoint in Next.js with integrated antivirus scanning.
Setting Up the API Route
First, create a Next.js API route handler at app/upload/route.ts:
import { NextRequest, NextResponse } from "next/server"
const ATTACHMENTAV_API_KEY = process.env.ATTACHMENTAV_API_KEY;
const ATTACHMENTAV_URL = 'https://eu.developer.attachmentav.com/v1/scan/sync/binary';
async function submitFileForMalwareScan(file: File) {
const buffer = await file.arrayBuffer();
return await fetch(ATTACHMENTAV_URL, {
method: 'POST',
headers: {
'x-api-key': ATTACHMENTAV_API_KEY,
'Content-Type': 'application/octet-stream',
},
body: buffer,
});
}
export async function POST(req: NextRequest) {
const formData = await req.formData();
const file = formData.get('file') as File;
if (!file) {
return NextResponse.json({ error: 'No file provided' }, { status: 400 });
}
// Submit file for virus scanning
const response = await submitFileForMalwareScan(file);
const scanResult = await response.json();
// Block infected files
if (scanResult.status === 'infected') {
return NextResponse.json({
error: 'Malware detected',
details: scanResult,
}, { status: 400 });
}
// File is clean - proceed with processing
return NextResponse.json({
message: 'File uploaded and scanned successfully',
filename: file.name,
scan: scanResult,
});
}
For a complete implementation, check out the full example on GitHub.
How the Antivirus Middleware Works
This API route acts as middleware by:
- Receiving the uploaded file from the frontend via FormData
- Converting to binary using
arrayBuffer()for transmission - Forwarding to attachmentAV with authentication headers
- Analyzing scan results - infected files return a 400 error
- Only allowing clean files to proceed through your application
Frontend Integration
The frontend implementation is straightforward:
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/upload', {
method: 'POST',
body: formData,
});
const data = await response.json();
if (response.ok) {
console.log('File scanned and safe:', data.scan.status);
} else {
console.error('Malware detected:', data.error);
}
Key Security Benefits
This implementation provides several security advantages:
- Synchronous scanning - Files are scanned before entering your system
- API key protection - Keys stored in environment variables, never exposed to clients
- Zero client-side bypassing - All validation happens server-side
- Immediate threat blocking - Infected files are rejected instantly
Scaling to Multiple Files
While we’ve focused on single file uploads, the same pattern extends to multiple files. The example repository includes a multi-file upload implementation that scans up to 3 files concurrently using a rate limiter. For details on implementing batch uploads with malware scanning, see the README.md in the repository.
Getting Started
To implement this solution in your own Next.js application:
- Install dependencies:
npm install next - Sign up for an attachmentAV API key at attachmentav.com
- Add your API key to
.env.local:ATTACHMENTAV_API_KEY=your_key_here - Create the API route as shown above
- Test with sample files to verify malware detection
Best Practices for Virus Scanning in Node.js Applications
When implementing antivirus scanning in your Node.js or Next.js application:
- Always scan server-side - Never rely on client-side validation alone
- Handle errors gracefully - Provide clear feedback when malware is detected
- Use environment variables - Keep API keys secure and out of source control
- Implement rate limiting - For multi-file uploads, limit concurrent API requests
- Log scan results - Maintain audit trails of detected threats
- Validate file types - Combine scanning with file type verification
Conclusion
Integrating antivirus and malware scanning into your Next.js API routes is essential for applications accepting user uploads. By using a dedicated scanning API like attachmentAV, you can implement robust virus detection as middleware without maintaining complex antivirus infrastructure yourself.
This approach works for any Node.js framework, though we’ve focused on Next.js API routes here. The same pattern applies to Express.js middleware, NestJS guards, or any other Node.js backend architecture.
Ready to secure your file uploads? Get started with attachmentAV today and protect your application from malware threats.
Published on February 17, 2026 | Written by Sebastian