Skip to main content
Security Guides

Secure File Uploads in Next.js: Validation, Malware Scanning, and Storage Isolation

SecuriSky TeamApril 18, 202612 min read

Securing File Uploads in Next.js

To secure file uploads in Next.js, you need to validate user input, scan files for malware, and store them in an isolated environment. This can be achieved by using a combination of validation libraries, malware scanning tools, and cloud storage services.

Validating user input is crucial to prevent malicious files from being uploaded to your server. You can use libraries like multer to handle multipart/form-data requests and validate file types. For example, you can use the following code to validate file types:

import multer from 'multer';

const upload = multer({

fileFilter(req, file, cb) { if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) { return cb(new Error('Only image files are allowed!')); } cb(null, true); },

});

This code will only allow files with .jpg, .jpeg, or .png extensions to be uploaded.

Malware scanning is another critical aspect of securing file uploads. You can use tools like clamav to scan files for malware. Here's an example of how you can use clamav to scan files:

import pyclamd

cd = pyclamd.ClamdNetworkSocket()

cd.ping()

Scan a file for malware

scan_result = cd.scan('/path/to/file')

if scan_result:

print('Malware detected!')

else:

print('File is clean.')

This code will scan a file for malware using clamav and print the result.

Storage isolation is also important to prevent malicious files from being executed on your server. You can use cloud storage services like AWS S3 to store files in an isolated environment. Here's an example of how you can use AWS S3 to store files:

import AWS from 'aws-sdk';

const s3 = new AWS.S3({

accessKeyId: 'YOUR_ACCESS_KEY', secretAccessKey: 'YOUR_SECRET_KEY',

});

const params = {

Bucket: 'your-bucket', Key: 'file.txt', Body: 'Hello World!',

};

s3.upload(params, (err, data) => {

if (err) { console.log(err); } else { console.log(data); }

});

This code will upload a file to an AWS S3 bucket.

To take it a step further, you can use a security scanner like SecuriSky to detect potential security issues in your Next.js application, including insecure file uploads.

In addition to validating user input, scanning files for malware, and storing them in an isolated environment, you should also consider implementing additional security measures such as authentication and authorization. Here's an example of how you can use authentication to restrict access to file uploads:

import { NextApiRequest, NextApiResponse } from 'next';

const authenticate = (req: NextApiRequest, res: NextApiResponse) => {

const token = req.headers.authorization; if (!token) { return res.status(401).json({ error: 'Unauthorized' }); } // Verify the token const verified = verifyToken(token); if (!verified) { return res.status(401).json({ error: 'Invalid token' }); } return true;

};

const handleFileUpload = (req: NextApiRequest, res: NextApiResponse) => {

if (!authenticate(req, res)) { return; } // Handle file upload

};

This code will restrict access to file uploads to only authenticated users.

Quick Fix Checklist

  • [ ] Validate user input using a library like multer
  • [ ] Scan files for malware using a tool like clamav
  • [ ] Store files in an isolated environment using a cloud storage service like AWS S3
  • [ ] Implement authentication and authorization to restrict access to file uploads
  • [ ] Use a security scanner like SecuriSky to detect potential security issues in your Next.js application
  • Try it free

    Scan your app for these issues now

    Paste your URL and get a full security, performance, and SEO report in under 2 minutes — no signup required.

    Run a free scan