Multer is Express middleware for handling multipart/form-data — the format used for file uploads.
Install
npm install multer
Configure storage
multer({ dest: 'uploads/' })— quick: saves with random names and no extensionmulter.diskStorage({ destination, filename })— choose the folder and a safe namemulter.memoryStorage()— keep the file in memory, e.g. to send to cloud storage
Limits and filters
limits: { fileSize: 2 * 1024 * 1024 }— 2 MBfileFilter— accept only allowed MIME types (images, PDF)
Use it on a route
upload.single('photo')→req.fileupload.array('photos', 5)→req.files- Other form fields are in
req.body
The HTML form
Needs method="post" and enctype="multipart/form-data". With fetch, send a FormData object.
Serve uploads with express.static('uploads'). For production, cloud storage (S3, Cloudinary) is better than the server's disk.
Example
Example — Image upload with limits
JavaScript
import express from 'express';
import multer from 'multer';
import path from 'node:path';
import crypto from 'node:crypto';
const app = express();
app.use('/uploads', express.static('uploads'));
const storage = multer.diskStorage({
destination: 'uploads/',
filename: (req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
cb(null, crypto.randomUUID() + ext);
},
});
const upload = multer({
storage,
limits: { fileSize: 2 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const ok = ['image/jpeg', 'image/png', 'image/webp'].includes(file.mimetype);
cb(ok ? null : new Error('Only JPG, PNG or WEBP images are allowed'), ok);
},
});
app.post('/api/avatar', upload.single('photo'), (req, res) => {
res.status(201).json({ url: `/uploads/${req.file.filename}`, size: req.file.size });
});
app.use((err, req, res, next) => res.status(400).json({ error: err.message }));
app.listen(3000);
Uploading a 500 KB JPG returns {"url":"/uploads/3f2a...jpg","size":512000}. A PDF or a 5 MB image returns 400 with an error message.