Multer is the most popular and reliable middleware for handling file uploads in Node.js and Express.js applications. File uploads are one of those features that seem simple until you actually try to implement them securely. I've dealt with everything from users uploading 500MB files that crash the server to malicious files that could compromise the system.
When I first started working with file uploads in Express.js, I quickly learned that handling multipart/form-data isn't as straightforward as it appears. That's where Multer comes in. Multer is a middleware specifically designed for handling file uploads in Express.js and Node.js applications.
What is Multer?
Multer is a Node.js middleware for handling multipart/form-data, which is primarily used for uploading files. Multer is the most popular solution for handling file uploads in Node.js and Express.js applications.
What is express multer? Express multer is the integration of multer middleware with Express.js. Express multer processes the multipart/form-data that browsers send when submitting forms with file inputs.
What is node multer? Node multer refers to using multer in Node.js applications. Multer works with any Node.js framework, not just Express.js.
Installation
Installing multer is straightforward:
npm install multer
For TypeScript projects, also install the types:
npm install --save-dev @types/multer @types/express
Basic Configuration
Setting up multer with disk storage is the most common configuration:
const multer = require("multer");
const path = require("path");
const fs = require("fs");
// Create uploads directory if it doesn't exist
const uploadDir = "uploads/";
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, uploadDir);
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 10000);
const ext = path.extname(file.originalname);
cb(null, file.fieldname + "-" + uniqueSuffix + ext);
},
});
const upload = multer({
storage: storage,
limits: {
fileSize: 5 * 1024 * 1024, // 5MB limit
},
fileFilter: (req, file, cb) => {
// Only allow images
if (file.mimetype.startsWith("image/")) {
cb(null, true);
} else {
cb(new Error("Only image files are allowed!"), false);
}
},
});
Single File Upload
Here's how to handle a single file upload:
const uploadSingleFile = upload.single("file");
function storeSingleFile(req, res, next) {
return new Promise((resolve, reject) => {
uploadSingleFile(req, res, async function (err) {
if (err instanceof multer.MulterError) {
reject(err);
} else if (err) {
reject(err);
}
resolve({
message: "File uploaded successfully",
file: req.file ? req.file : null,
});
});
});
}
// Usage in route
app.post("/upload", async (req, res) => {
try {
const result = await storeSingleFile(req, res);
res.json(result);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
Multiple File Upload
For multiple files:
const uploadMultipleFiles = upload.array("files", 10); // Max 10 files
app.post("/upload-multiple", uploadMultipleFiles, (req, res) => {
try {
const files = req.files;
res.json({
message: "Files uploaded successfully",
files: files.map(file => ({
filename: file.filename,
originalname: file.originalname,
size: file.size,
})),
});
} catch (error) {
res.status(400).json({ error: error.message });
}
});
Best Practices
- Set file size limits
- Validate file types
- Use unique filenames
- Handle errors gracefully
- Clean up temporary files
- Consider cloud storage for production
📖 Read the Complete Guide
This is just a brief overview! The complete guide on my blog includes:
- ✅ File Buffer Handling - Working with file buffers
- ✅ Cloud Storage Integration - Uploading to S3, Cloudinary
- ✅ Error Handling - Comprehensive error management
- ✅ TypeScript Setup - Type-safe file uploads
- ✅ Security Best Practices - File validation and security
- ✅ Real-world examples from production applications
👉 Read the full article with all code examples here
What's your experience with Multer? Share your tips in the comments! 🚀
For more backend guides, check out my blog covering Cloudinary, Express.js, Prisma ORM, and more.
Top comments (0)