Handling File Uploads in Node.js: Multer, Streams and S3 Presigned URLs
File uploads look simple and cause many production problems: memory spikes, huge files, malicious content, and slow servers.
Option 1: Through Your Server (Multer)
import multer from 'multer';
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB
fileFilter: (req, file, cb) => cb(null, ['image/png', 'image/jpeg'].includes(file.mimetype)),
});
app.post('/avatar', upload.single('avatar'), async (req, res) => {
await saveToStorage(req.file.buffer, req.file.originalname);
res.json({ ok: true });
});
Fine for small files. For large files, stream instead of buffering in memory.
Option 2: Presigned URLs (Recommended)
The client uploads directly to S3 (or compatible storage) using a short-lived signed URL from your server:
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
const s3 = new S3Client({ region: 'ap-south-1' });
app.post('/upload-url', async (req, res) => {
const key = `uploads/${req.user.id}/${crypto.randomUUID()}`;
const url = await getSignedUrl(s3, new PutObjectCommand({ Bucket: 'my-bucket', Key: key, ContentType: req.body.type }), { expiresIn: 300 });
res.json({ url, key });
});
Your server never handles the file bytes — it scales much better.
Security Checklist
- Limit file size
- Validate type by content, not just extension
- Generate your own file names — never trust user file names
- Store uploads outside the web root, in private buckets
- Scan for malware for user-shared files
- Serve through signed URLs if files are private
Let storage services handle file bytes; let your Node.js app handle permissions and metadata.