Skip to content

widdix/attachmentav-example-nodejs-nextjs

Repository files navigation

attachmentAV Next.js Example

This is a Next.js example application demonstrating file upload with malware scanning using the attachmentAV API. It showcases how to integrate real-time virus scanning into your web application to protect users from malicious files.

Architecture Diagram

┌─────────────────┐
│  User Browser   │
└────────┬────────┘
         │
         │ POST /upload (single file)
         │ POST /multiupload (multiple files)
         ▼
┌─────────────────┐
│ Next.js App     │
│ (API Routes)    │
└────────┬────────┘
         │
         │ POST /v1/scan/sync/binary
         │ (max 3 concurrent for multiupload)
         ▼
┌─────────────────┐
│ attachmentAV    │
│ API             │
└─────────────────┘

Getting Started

Prerequisites

Step 1: Clone and Install Dependencies

# Install dependencies
npm install
# or
yarn install
# or
pnpm install

Step 2: Configure API Key

Create a .env.local file in the root directory and add your attachmentAV API key:

ATTACHMENTAV_API_KEY=your_api_key_here

Step 3: Run the Development Server

npm run dev
# or
yarn dev
# or
pnpm dev

Step 4: Test the Application

Open http://localhost:3000 in your browser. You should see two file upload forms:

Single File Upload:

  1. Select a file from your computer
  2. Click "Upload File"
  3. View the scan results (clean or infected)

Scan results of uploading a single file

Multi File Upload:

  1. Select multiple files from your computer
  2. Click "Upload Files"
  3. View the scan results for all files (scanned with max 3 concurrent requests)

Scan results of uploading multiple files

How It Works

Frontend (app/page.tsx)

The frontend is a React component that provides two file upload interfaces:

Single File Upload

  1. File Selection: Uses an HTML file input to let users select one file
  2. Form Submission: Creates a FormData object containing the file
  3. API Call: Sends a POST request to /upload with the file data
  4. Result Display: Shows success/error messages based on the scan results

Multi File Upload

  1. File Selection: Uses an HTML file input with multiple attribute to let users select multiple files
  2. Form Submission: Creates a FormData object containing all selected files
  3. API Call: Sends a POST request to /multiupload with all files
  4. Result Display: Shows aggregated results for all files with individual status per file

Key features:

  • Two side-by-side upload forms (responsive design)
  • Disables forms during upload to prevent multiple submissions
  • Displays the selected filename(s) and count
  • Shows color-coded success (green) or error (red) messages
  • Displays detailed scan results for each file in multi-upload
  • Automatically resets forms after successful upload

Backend - Single Upload (app/upload/route.ts)

The API route handles the server-side logic for single file malware scanning:

  1. Receive File: Extracts the file from the incoming FormData request
  2. Convert to Buffer: Converts the file to an ArrayBuffer for transmission
  3. Submit to attachmentAV:
    • Sends the binary data to the attachmentAV API endpoint
    • Includes the API key in the x-api-key header
    • Sets Content-Type: application/octet-stream for binary data
  4. Process Results: Analyzes the scan response:
    • status: 'infected' → Returns 400 error with malware details
    • status: 'no' → Logs warning (file couldn't be scanned)
    • status: 'clean' → Returns success response
  5. Return Response: Sends the scan results back to the frontend

Backend - Multi Upload (app/multiupload/route.ts)

The multi-upload API route handles parallel scanning of multiple files with concurrency control:

  1. Receive Files: Extracts all files from the incoming FormData using formData.getAll('file')
  2. Initialize Concurrency Limiter: Uses p-limit with MAX_CONCURRENT_REQUESTS = 3 to limit parallel scans
  3. Parallel Scanning:
    • Maps each file to a scan promise wrapped with the limiter
    • Ensures only 3 files are scanned simultaneously
    • Queues remaining files until a slot becomes available
  4. Individual File Processing: For each file:
    • Converts to ArrayBuffer
    • Submits to attachmentAV API
    • Captures scan results or errors
  5. Aggregate Results: Collects all scan results and checks for:
    • Infected files → Returns 400 error with details
    • Scan failures → Returns 500 error with details
    • All clean → Returns 200 success with all results
  6. Return Response: Sends comprehensive results for all files back to the frontend

Key features:

  • Concurrency Control: Uses p-limit to prevent overwhelming the API
  • Individual Error Handling: Each file scan is isolated; one failure doesn't stop others
  • Detailed Results: Returns status for every file in the batch
  • Configurable Limit: MAX_CONCURRENT_REQUESTS constant for easy adjustment

Security Features

  • API key is stored in environment variables (never exposed to the client)
  • File validation on both client and server
  • Synchronous scanning ensures malware is detected before the file is processed
  • Error handling for API failures and network issues

attachmentAV Integration

The application uses the synchronous binary scan endpoint:

  • Endpoint: https://eu.developer.attachmentav.com/v1/scan/sync/binary
  • Method: POST
  • Authentication: API key via x-api-key header
  • Content: Raw binary file data

The API returns a JSON response with:

{
  "status": "clean" | "infected" | "no",
  // Additional scan metadata
}

Project Structure

.
├── app/
│   ├── page.tsx           # Frontend with single and multi-file upload forms
│   ├── upload/
│   │   └── route.ts       # Backend API route for single file scanning
│   ├── multiupload/
│   │   └── route.ts       # Backend API route for multi-file scanning (max 3 concurrent)
│   └── ...
├── .env.local             # Environment variables (create this)
└── package.json

Learn More

Deploy on Vercel

The easiest way to deploy your Next.js app is to use the Vercel Platform.

Remember to add your ATTACHMENTAV_API_KEY environment variable in the Vercel project settings.

About

Scan files for malware in Next.js with the attachmentAV API

Topics

Resources

Stars

Watchers

Forks