Almost every product stores files: profile pictures, invoices, resumes, attachments. This project is a small version of a cloud drive: users upload files, list them, download them and delete them, and every file belongs to its owner. It combines three earlier lessons, the safe uploads of lesson 22, the roles and tokens of lesson 27 and the interface idea of dependency injection, so that the bytes can live on a disk today and in the cloud tomorrow.
What you will build
POST /api/filesuploads a file in the fieldfile, for logged-in users.- Allowed types: PNG, JPEG, PDF and plain text, from an allow-list.
- A storage quota for each user.
GET /api/fileslists your files, andGET /api/files/:iddownloads one.DELETE /api/files/:idremoves the bytes and the record.- A driver with three functions,
put,getandremove, so that storage is replaceable.
Design decisions before any code
Two things are stored for each upload: the bytes, which go to the driver under a random key, and a record, with the owner, the original name, the real type, the size and the key. The user's original file name is kept only as a label. It is never used to build a path. The record is what the API lists and checks. A file belongs to a person if and only if record.ownerId equals the user from the token.
Because the driver is a small interface, the tests run with a folder in the operating system's temporary directory, and production can use a cloud driver. The second file below shows the same three functions on ImageKit, which is how the main server of this site stores its images. It was not run, because it needs an account and keys, so read it as a pattern and follow the current documentation of the service.
- 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 jsonwebtoken. - Copy
p-kit.js,p08-files.jsandp08.test.jsinto the folder. The sharedp-kit.jsis in Project 1. - Install the test tools with
npm install -D supertest, then runnode --test p08.test.js.
The API and the local-folder driver. Read the upload route to see the order of checks: type, then quota, then save.
// Project 8: a file storage API. Upload, list, download and delete, with owners and a storage driver.
import express from 'express';
import multer from 'multer';
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { AppError, requireAuth, errorHandler, notFoundHandler } from './p-kit.js';
const MAX_BYTES = 2 * 1024 * 1024;
const QUOTA_BYTES = 5 * 1024 * 1024; // per user
const TYPES = { 'image/png': '.png', 'image/jpeg': '.jpg', 'application/pdf': '.pdf', 'text/plain': '.txt' };
// A driver saves, reads and deletes bytes. This one uses a folder. A Cloudinary or ImageKit driver has the same three functions.
export function folderDriver(folder) {
return {
async put(key, buffer) { await fs.writeFile(path.join(folder, key), buffer); },
async get(key) { return fs.readFile(path.join(folder, key)); },
async remove(key) { await fs.rm(path.join(folder, key), { force: true }); },
};
}
export function createApp({ driver }) {
const app = express();
const auth = requireAuth();
const files = new Map(); // id -> metadata (in production: a database table)
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_BYTES, files: 1 } });
const usedBytes = (userId) => [...files.values()].filter((f) => f.ownerId === userId).reduce((sum, f) => sum + f.size, 0);
app.post('/api/files', auth, upload.single('file'), async (req, res) => {
const file = req.file;
if (!file) throw new AppError('Send a file in the field "file"', 400);
const extension = TYPES[file.mimetype];
if (!extension) throw new AppError('Allowed types: PNG, JPEG, PDF and plain text', 415);
if (usedBytes(req.user.id) + file.size > QUOTA_BYTES) throw new AppError('Storage quota reached', 413);
const id = crypto.randomUUID();
const key = id + extension; // the stored name never comes from the user
await driver.put(key, file.buffer);
const record = { id, key, ownerId: req.user.id, originalName: path.basename(file.originalname), mimetype: file.mimetype, size: file.size, createdAt: new Date().toISOString() };
files.set(id, record);
res.status(201).json({ id, name: record.originalName, size: record.size });
});
const mine = (req) => {
const record = files.get(req.params.id);
if (!record || record.ownerId !== req.user.id) throw new AppError('File not found', 404); // 404, not 403: do not reveal that it exists
return record;
};
app.get('/api/files', auth, (req, res) => {
const list = [...files.values()].filter((f) => f.ownerId === req.user.id).map(({ key, ownerId, ...rest }) => rest);
res.json({ files: list, usedBytes: usedBytes(req.user.id), quotaBytes: QUOTA_BYTES });
});
app.get('/api/files/:id', auth, async (req, res) => {
const record = mine(req);
res.set({
'Content-Type': record.mimetype,
'Content-Disposition': `attachment; filename="${encodeURIComponent(record.originalName)}"`,
'X-Content-Type-Options': 'nosniff', // the browser must not guess a different type
});
res.send(await driver.get(record.key));
});
app.delete('/api/files/:id', auth, async (req, res) => {
const record = mine(req);
await driver.remove(record.key);
files.delete(record.id);
res.status(204).end();
});
app.use((err, req, res, next) => {
if (err instanceof multer.MulterError) return errorHandler(new AppError(err.message, err.code === 'LIMIT_FILE_SIZE' ? 413 : 400), req, res, next);
errorHandler(err, req, res, next);
});
app.use(notFoundHandler);
return app;
}
The same driver interface for ImageKit. For cloud storage, you normally serve files by URL, so get explains that.
// The same driver interface on ImageKit (this is how the main server of this site stores files).
// NOT run in this course: it needs an ImageKit account and IMAGEKIT_PRIVATE_KEY. npm install @imagekit/nodejs
import ImageKit from '@imagekit/nodejs';
const imagekit = new ImageKit({ privateKey: process.env.IMAGEKIT_PRIVATE_KEY });
export function imagekitDriver() {
const ids = new Map(); // key -> ImageKit file id (keep this in your database in a real app)
return {
async put(key, buffer) {
const uploaded = await imagekit.files.upload({ file: buffer.toString('base64'), fileName: key });
ids.set(key, uploaded.fileId);
},
async get(key) {
throw new Error('Serve ImageKit files by their URL instead of through your server');
},
async remove(key) {
if (ids.has(key)) await imagekit.files.delete(ids.get(key));
},
};
}
The test uploads allowed files, an .exe file, a file that is too large and uploads that pass the quota, and then tests downloads and deletes by the owner and by someone else.
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, folderDriver } from './p08-files.js';
import { signToken } from './p-kit.js';
const as = (id) => ({ Authorization: `Bearer ${signToken({ id, role: 'user', name: `u${id}` })}` });
test('project 8: upload, owner checks, download, delete, quota', async () => {
const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'files-'));
const app = createApp({ driver: folderDriver(folder) });
assert.equal((await request(app).post('/api/files').attach('file', Buffer.from('hi'), { filename: 'a.txt', contentType: 'text/plain' })).status, 401);
const up = await request(app).post('/api/files').set(as(1)).attach('file', Buffer.from('hello world'), { filename: '../../evil name.txt', contentType: 'text/plain' });
assert.equal(up.status, 201);
assert.equal(up.body.name, 'evil name.txt'); // path parts are removed
assert.equal(fs.readdirSync(folder).length, 1);
assert.match(fs.readdirSync(folder)[0], /^[0-9a-f-]{36}\.txt$/);
assert.equal((await request(app).post('/api/files').set(as(1)).attach('file', Buffer.from('x'), { filename: 'a.exe', contentType: 'application/x-msdownload' })).status, 415);
assert.equal((await request(app).post('/api/files').set(as(1)).attach('file', Buffer.alloc(3 * 1024 * 1024), { filename: 'big.txt', contentType: 'text/plain' })).status, 413);
const list = await request(app).get('/api/files').set(as(1));
assert.equal(list.body.files.length, 1);
assert.equal((await request(app).get('/api/files').set(as(2))).body.files.length, 0);
const download = await request(app).get(`/api/files/${up.body.id}`).set(as(1));
assert.equal(download.text, 'hello world');
assert.equal(download.headers['x-content-type-options'], 'nosniff');
assert.equal((await request(app).get(`/api/files/${up.body.id}`).set(as(2))).status, 404); // not the owner
assert.equal((await request(app).delete(`/api/files/${up.body.id}`).set(as(2))).status, 404);
// Quota: two 2 MB files fit, the third does not.
const two = Buffer.alloc(2 * 1024 * 1024 - 1, 'a');
assert.equal((await request(app).post('/api/files').set(as(3)).attach('file', two, { filename: '1.txt', contentType: 'text/plain' })).status, 201);
assert.equal((await request(app).post('/api/files').set(as(3)).attach('file', two, { filename: '2.txt', contentType: 'text/plain' })).status, 201);
assert.equal((await request(app).post('/api/files').set(as(3)).attach('file', two, { filename: '3.txt', contentType: 'text/plain' })).status, 413);
assert.equal((await request(app).delete(`/api/files/${up.body.id}`).set(as(1))).status, 204);
assert.equal(fs.readdirSync(folder).length, 2);
fs.rmSync(folder, { recursive: true });
});
Rules worth understanding
An allow-list of types. Only four types are accepted, and anything else is refused with 415. This project trusts the type that the upload declares. That is a weakness, because a client can lie about it, and lesson 22 shows the stronger check of reading the first bytes. Adding that check is the first extension task.
A quota per user. Before saving, the code adds the new size to what the user already stores. If the total goes above the quota, the reply is 413. Without a quota, one account can fill your disk or your cloud bill.
404 instead of 403. If the file exists but belongs to someone else, the reply is File not found. A 403 would reveal that a file with that id exists, and ids can be guessed.
Clean up both sides. Deleting removes the bytes from the driver and the record from the list. If the first step fails, the record must stay, so you can try again.
Download headers. Send the stored type, and for types that a browser could run, such as HTML, force a download with Content-Disposition: attachment. This project does not allow HTML at all.
Security and honesty notes
The names given by the user are never part of a path, and the key is a random UUID with an extension that the server chose. Files are stored outside the folders that Express serves as static content. Ask whether uploaded files could contain malware, and if the files are shared with others, add a virus scan.
Edge cases are where upload bugs live, so test a file that is too large, a type that is not allowed, and a user who is exactly at the limit of the quota.
Extend it
Your task
- Add the first-bytes type check from lesson 22 and a test with a fake PNG.
- Write a driver for Amazon S3 or Cloudinary from the three-function interface.
- Add signed, expiring download links.
- Add folders, with a rule that a user cannot see another user's folders.
How to check it worked
- An
.exeupload is refused with 415. - Another user receives 404 for your file.
- Deleting removes both the record and the stored bytes.
On your resume. "Built a file storage API with an allow-list of types, per-user quotas, owner-only access and a swappable storage driver for local disk and ImageKit" describes it well. Do not claim the cloud driver works in production unless you have run it. Write only what you really built and can explain, and keep the repository link next to it. Our resume templates have a project section that suits this, and the ATS checker shows how a tracking system reads it.