File uploads
Overview
Profile photos, documents, CSV imports, assignment submissions — most apps need to accept files. Uploads are also one of the riskiest features you can build: they let strangers put arbitrary bytes onto your systems. Done carelessly, they enable denial of service (huge files), malware hosting, overwriting other files, and even running code on your server.
This topic shows how to accept files safely, and where to store them.
How browsers send files
A JSON body can’t carry binary files efficiently. Browsers use multipart/form-data: the body is split into parts, one per form field, each with its own headers:
<form action="/me/avatar" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" accept="image/*">
<button>Upload</button>
</form>From JavaScript:
const body = new FormData();
body.append('avatar', fileInput.files[0]);
await fetch('/me/avatar', { method: 'PUT', body }); // the browser sets the Content-Typeexpress.json() ignores multipart bodies, so you need a parser for them. multer is the standard choice for Express.
npm install multerReceiving a file with multer
import multer from 'multer';
const upload = multer({
storage: multer.memoryStorage(), // keep the file in a Buffer (fine for small files)
limits: {
fileSize: 5 * 1024 * 1024, // 5 MB
files: 1, // at most one file
fields: 10, // and a few text fields
},
});
app.post('/documents', requireLogin, upload.single('document'), async (req, res) => {
console.log(req.file);
// {
// fieldname: 'document', originalname: 'report.pdf', mimetype: 'application/pdf',
// size: 183245, buffer: <Buffer 25 50 44 46 …>
// }
console.log(req.body); // other text fields from the form
// …validate and store
});Other options: upload.array('photos', 5) for several files in one field, upload.fields([...]) for several fields, and multer.diskStorage({...}) to stream large files to a temporary folder instead of memory.
Limit errors
When a limit is exceeded, multer passes a MulterError to your error handler. Turn it into a proper status code:
if (err instanceof multer.MulterError) {
const status = err.code === 'LIMIT_FILE_SIZE' ? 413 : 400;
return res.status(status).json({ error: { message: err.message } });
}Never trust what the client says
Everything about an upload comes from the client and can be faked:
| Field | Can be faked? | What to do |
|---|---|---|
originalname (cat.jpg) |
yes — could be ../../app.js or invoice.pdf.exe |
never use it as a path; store your own name |
mimetype (image/jpeg) |
yes — it’s just a header | check the actual bytes |
size |
enforced by multer’s limits | set limits |
Check the content. Most file formats start with a recognisable signature (“magic number”):
function detectImage(buf) {
if (buf.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return 'jpg';
if (buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
if (buf.toString('latin1', 0, 4) === 'RIFF' && buf.toString('latin1', 8, 12) === 'WEBP') return 'webp';
return null;
}The file-type package detects hundreds of formats this way. For images, re-encoding them with a library such as sharp (resizing as you go) is an even stronger defence: it strips hidden data and anything that isn’t a real image.
Generate your own names, such as ${randomUUID()}.png. Store the original name in your database if you want to show it — never use it as a path.
For documents shared with other users, consider virus scanning (for example ClamAV) before making them available.
Where to store files
Saving uploads to the app server’s disk is tempting, but it causes problems in production:
- Containers and many hosting platforms wipe the disk on every deployment.
- With several app instances, a file saved on one isn’t on the others.
- Disks fill up, and backups get complicated.
Use object storage instead — Amazon S3, Cloudflare R2, Google Cloud Storage, Azure Blob Storage, or self-hosted MinIO. They store unlimited files cheaply and durably, and serve them fast. Most speak the S3 API, so one client library works with all of them:
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
const s3 = new S3Client({ region: process.env.S3_REGION, endpoint: process.env.S3_ENDPOINT });
await s3.send(new PutObjectCommand({
Bucket: process.env.S3_BUCKET,
Key: `avatars/${user.id}/${randomUUID()}.png`,
Body: req.file.buffer,
ContentType: 'image/png',
}));Save the object’s key in your database (e.g. on the user row), not the file itself.
Large files: presigned uploads
Passing a 2 GB video through your Node server ties up memory, bandwidth and a connection for minutes. Instead, let the browser upload directly to storage. Your API only hands out permission:
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
app.post('/uploads/presign', requireLogin, validate({ body: presignSchema }), async (req, res) => {
const key = `videos/${req.user.id}/${randomUUID()}.mp4`;
const url = await getSignedUrl(
s3,
new PutObjectCommand({ Bucket: process.env.S3_BUCKET, Key: key, ContentType: 'video/mp4' }),
{ expiresIn: 300 }, // valid for 5 minutes
);
res.json({ url, key });
});The browser PUTs the file to url, then tells your API the upload finished (sending key). Your server never handles the bytes. A background job can then check the file and process it.
Serving files back
- Public files (avatars, course images): serve from the storage bucket or a CDN in front of it.
- Private files (invoices, submissions): keep the bucket private, check permissions in your API, then redirect to a short-lived presigned download URL (
GetObjectCommand+getSignedUrl). - If you ever serve user files from your own domain, set
Content-Disposition: attachmentand the correctContent-Typeso an uploaded HTML file can’t run scripts on your site.
Upload checklist: limits on size and count · content-based type checks · random storage names · object storage, not local disk · private by default · processing in a background job.
An avatar upload endpoint
Create PUT /me/avatar that accepts one file field named avatar: at most 2 MB, JPEG/PNG/WebP only. Check the file's first bytes (not just its MIME type), save it under a random name, and return its URL. Respond 413 for too-large files and 415 for wrong types.
import multer from 'multer';
const upload = multer({
// your options here
});
app.put('/me/avatar', requireLogin, upload.single('avatar'), async (req, res) => {
// your code here
});import multer from 'multer';
import { randomUUID } from 'node:crypto';
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 2 * 1024 * 1024, files: 1 },
});
function detectImage(buf) {
if (buf.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return 'jpg';
if (buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
if (buf.toString('latin1', 0, 4) === 'RIFF' && buf.toString('latin1', 8, 12) === 'WEBP') return 'webp';
return null;
}
app.put('/me/avatar', requireLogin, upload.single('avatar'), async (req, res) => {
if (!req.file) throw new HttpError(400, 'Attach an image in the "avatar" field');
const ext = detectImage(req.file.buffer);
if (!ext) throw new HttpError(415, 'Only JPEG, PNG or WebP images are allowed');
const name = `${randomUUID()}.${ext}`;
await writeFile(path.join(UPLOAD_DIR, name), req.file.buffer);
res.json({ url: `/uploads/${name}` });
});
// in the error handler:
// if (err instanceof multer.MulterError && err.code === 'LIMIT_FILE_SIZE') → 413Summary
- Browsers send files as
multipart/form-data;express.json()can’t read it — use multer. - Always set limits on file size and count, and reject unexpected fields.
- Don’t trust the file name, extension or MIME type — check the content and generate your own names.
- Store files in object storage (S3, R2, GCS), not on the app server’s disk.
- For large files, let the browser upload directly to storage with a presigned URL.