Letting users upload files is one of the riskiest features you can add. A profile photo or a PDF resume feels harmless, but the file is data from a stranger that you will store, and perhaps show to other people. Careless upload code has led to servers being taken over, disks being filled and private files being leaked. This lesson shows the safe way, using the Multer package, and a tested example.
How uploads work
A normal JSON body cannot carry a file well, so browsers use multipart/form-data, which splits a request into named parts, some text and some files. Express does not read this format, so Multer does. It reads the parts and gives you req.file for one upload or req.files for many. You choose where the bytes go: to the disk, or into memory as a Buffer.
Five rules for safe uploads
- Set a size limit. Without one, a single request can fill your memory or your disk. Here it is 1 MB.
- Check the real type. The
Content-Typeand the file name come from the client, who can lie. Look at the first bytes of the file, which are called the *magic number*. A PNG always starts with the same eight bytes, a PDF with%PDF-. - Use an allow-list of types you accept, instead of a block-list of bad ones.
- Make your own file name. A random UUID plus the extension you decided. Never use the original name to build a path, because a name such as
../../app.jsis an attack called path traversal. - Do not serve uploads as code. Store them outside your source folders, or in cloud storage, and send them with the correct type.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install express multer. - Save the code as
upload.js. The test needsnpm install -D supertest.
import express from 'express';
import multer from 'multer';
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
const MAX_BYTES = 1024 * 1024; // 1 MB
const ALLOWED = { 'image/png': '.png', 'image/jpeg': '.jpg', 'application/pdf': '.pdf' };
// Never trust the type the browser claims. Look at the first bytes of the file.
export function sniff(buffer) {
if (buffer.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'image/png';
if (buffer.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return 'image/jpeg';
if (buffer.subarray(0, 5).toString('latin1') === '%PDF-') return 'application/pdf';
return null;
}
// A storage "driver" has one job. Swap this one for Cloudinary or ImageKit later.
export function localStorageDriver(folder) {
return {
async save(buffer, extension) {
const name = crypto.randomUUID() + extension; // never use the original name
await fs.writeFile(path.join(folder, name), buffer);
return { name, url: `/files/${name}` };
},
};
}
export function createApp({ driver }) {
const app = express();
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: MAX_BYTES, files: 1 },
fileFilter: (req, file, cb) => cb(null, Boolean(ALLOWED[file.mimetype])),
});
app.post('/api/upload', upload.single('file'), async (req, res) => {
if (!req.file) return res.status(400).json({ error: 'Send one PNG, JPEG or PDF in the field "file"' });
const real = sniff(req.file.buffer);
if (real !== req.file.mimetype) return res.status(400).json({ error: 'The file content does not match its type' });
res.status(201).json(await driver.save(req.file.buffer, ALLOWED[real]));
});
// Multer errors (such as a file that is too big) arrive here.
app.use((err, req, res, next) => {
if (err instanceof multer.MulterError) {
const status = err.code === 'LIMIT_FILE_SIZE' ? 413 : 400;
return res.status(status).json({ error: err.message });
}
res.status(500).json({ error: 'Something went wrong' });
});
return app;
}
Read the code in the order a request travels. Multer's memoryStorage puts the file in req.file.buffer, and the limits option stops anything over 1 MB. Then sniff compares the first bytes with the known signatures. If the result is not in the allow-list, the route replies 415 or 422 and nothing is saved. Only a passed file is given a random name and handed to the storage driver.
A storage driver keeps your options open
Look at localStorageDriver: it has one method, save, that takes a buffer and a name and returns a URL. Everything else in the app uses that method only. When the project grows and local disk is no longer enough, because you have several servers or want a content delivery network, you write another driver with the same method that sends the file to Cloudinary, ImageKit or Amazon S3, and change one line where the app is created. That is the idea of a stable interface in front of a changeable detail, and project 8 in this course shows an ImageKit driver.
Handling Multer errors
When a limit is exceeded, Multer raises a MulterError, such as LIMIT_FILE_SIZE. If you do nothing, the client sees a confusing 500. The example catches it and returns 413 Payload Too Large with a clear message. Also reject requests that have no file at all, with 400.
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createApp, localStorageDriver, sniff } from './u22-upload.js';
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(20)]);
test('upload rules', async () => {
const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'up-'));
const app = createApp({ driver: localStorageDriver(folder) });
const ok = await request(app).post('/api/upload').attach('file', PNG, { filename: 'me.png', contentType: 'image/png' });
assert.equal(ok.status, 201);
assert.match(ok.body.name, /^[0-9a-f-]{36}\.png$/);
assert.equal(fs.readdirSync(folder).length, 1);
// A text file pretending to be a PNG is refused by the content check.
const fake = await request(app).post('/api/upload').attach('file', Buffer.from('not an image'), { filename: 'x.png', contentType: 'image/png' });
assert.equal(fake.status, 400);
// A type that is not allowed is skipped by the filter.
const bad = await request(app).post('/api/upload').attach('file', Buffer.from('hi'), { filename: 'x.txt', contentType: 'text/plain' });
assert.equal(bad.status, 400);
// Too big.
const big = await request(app).post('/api/upload').attach('file', Buffer.concat([PNG, Buffer.alloc(1024 * 1024)]), { filename: 'big.png', contentType: 'image/png' });
assert.equal(big.status, 413);
assert.equal(sniff(Buffer.from('%PDF-1.7')), 'application/pdf');
fs.rmSync(folder, { recursive: true });
});
The test sends a real PNG, a text file that pretends to be a PNG, a file that is too large, and a request with no file. Only the first is accepted. Run it with node --test and read what each case returns.
Beyond the basics
For large files, such as video, do not pass them through your server at all. Ask the cloud provider for a short-lived signed upload URL, and let the browser send the file straight to it. Your server only records the result. For images, resize and convert them on upload, because a 12 MB phone photo does not belong on a web page. For files that others will open, such as PDF resumes, consider a virus scan, which cloud storage services and tools like ClamAV can provide.
Your task
- Add GIF support, including its magic bytes, and a test.
- Change the limit to 200 KB for a profile photo and watch the 413 reply.
- Write a second driver that saves into a
uploads-bfolder and swap it in.
How to check it worked
- A real PNG returns a URL and a fake PNG is refused.
- A big file returns 413.
- No saved file uses the name the user sent.