Skip to content
jshacks.dev
Node.js

Build a File Upload Service With Node.js

Build a file upload service in Node.js that streams raw bodies to disk, enforces size and type limits, hashes content and serves downloads safely.

8 min read
Summarize in AI
Flat illustration of folders syncing with a cloud bucket, with the Node.js, Cloudflare, DigitalOcean, Linux and TypeScript logos.

A file upload endpoint is the place where a small service meets the worst of the internet. Clients send files of any size, with any name, claiming any type, over connections that stall or die halfway. Most upload bugs are not about parsing: they are about buffering a 4 GB body in memory, trusting a file name that contains ../, or leaving half a file on disk after a dropped connection. This post builds an upload service on Node.js 26 with node:http, node:stream/promises and node:crypto, using raw bodies instead of multipart forms, so you can see each defense and where it belongs.

Raw upload, not multipart

Multipart form data is what an HTML form sends, and parsing it correctly is real work, which is why people install multer or busboy. For an API, you can skip it. The client sends the file as the request body with PUT /files/<name> or POST /files, and sets content-type and content-length headers. The server reads a stream and never has to find boundaries. curl --data-binary @photo.jpg and fetch(url, { method: "PUT", body: file }) both work without a form.

The browser form path needs multipart, and for that case a parser is the right tool. For scripts, mobile apps and server-to-server transfers, the raw body is simpler and faster.

The design

The service accepts POST /files, streams the body to a temporary file while counting bytes and hashing, and then moves it to its final name. It answers with the id, size and SHA-256 hash. GET /files/:id streams it back. The final name is the hash plus nothing the client chose, which removes path traversal as a class of bug and deduplicates identical uploads for free.

Create a files directory for finished uploads and a tmp directory for partial ones, both on the same filesystem so that rename is atomic.

The upload handler

upload.jsJavaScript
import { createWriteStream } from "node:fs";
import { rename, rm, stat } from "node:fs/promises";
import { pipeline } from "node:stream/promises";
import { Transform } from "node:stream";
import { createHash, randomUUID } from "node:crypto";

const MAX_BYTES = 10 * 1024 * 1024;
const ALLOWED = new Set(["image/png", "image/jpeg", "application/pdf", "text/plain"]);

class Limit extends Transform {
  constructor(max) {
    super();
    this.max = max;
    this.seen = 0;
    this.hash = createHash("sha256");
  }
  _transform(chunk, _enc, done) {
    this.seen += chunk.length;
    if (this.seen > this.max) {
      return done(Object.assign(new Error("file too large"), { status: 413 }));
    }
    this.hash.update(chunk);
    done(null, chunk);
  }
}

export async function handleUpload(req) {
  const type = (req.headers["content-type"] ?? "").split(";")[0].trim();
  if (!ALLOWED.has(type)) {
    throw Object.assign(new Error(`type ${type || "none"} not allowed`), { status: 415 });
  }

  const declared = Number(req.headers["content-length"]);
  if (declared > MAX_BYTES) {
    throw Object.assign(new Error("file too large"), { status: 413 });
  }

  const tmp = new URL(`./tmp/${randomUUID()}`, import.meta.url);
  const limit = new Limit(MAX_BYTES);

  try {
    await pipeline(req, limit, createWriteStream(tmp));
    const digest = limit.hash.digest("hex");
    const final = new URL(`./files/${digest}`, import.meta.url);
    await rename(tmp, final);
    return { id: digest, size: limit.seen, type };
  } catch (err) {
    await rm(tmp, { force: true });
    throw err;
  }
}

Read the order of the checks, because it is the point. The type and the declared length are checked before any byte is read, so an oversized or disallowed upload is rejected cheaply. But content-length is a claim, and a client can lie or use chunked encoding with no length at all. The Limit transform is the real enforcement: it counts bytes as they arrive and fails the pipeline the moment the total passes the limit. Both checks are needed. The header check is a courtesy that saves bandwidth, and the counter is the guarantee.

pipeline from node:stream/promises is the right way to connect streams. It propagates errors and destroys every stream in the chain, which a bare .pipe() does not do. That is how a dropped connection stops leaving open file handles behind. On any failure the catch block removes the temporary file, so a half-written upload never reaches files.

Hashing while streaming costs almost nothing, since each chunk is already in memory. It gives you an integrity value to return to the client and a collision-resistant file name.

Serving files back

Downloads need two protections: the id must be validated before it touches the filesystem, and the response must not let the browser guess a type and run content.

download.jsJavaScript
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { pipeline } from "node:stream/promises";

const ID = /^[a-f0-9]{64}$/;

export async function handleDownload(id, res, typeFor) {
  if (!ID.test(id)) {
    res.writeHead(404);
    return res.end();
  }
  const file = new URL(`./files/${id}`, import.meta.url);
  let info;
  try {
    info = await stat(file);
  } catch {
    res.writeHead(404);
    return res.end();
  }
  res.writeHead(200, {
    "content-length": info.size,
    "content-type": typeFor(id) ?? "application/octet-stream",
    "x-content-type-options": "nosniff",
    "content-disposition": "attachment",
    "cache-control": "public, max-age=31536000, immutable",
  });
  await pipeline(createReadStream(file), res);
}

The ID pattern accepts only 64 hex characters, so ../../etc/passwd never reaches new URL. Because the file name is the content hash, the response can be cached forever: the same URL can only ever return the same bytes, which is what immutable promises. content-disposition: attachment makes browsers download instead of rendering, and nosniff stops them from reinterpreting a text file as HTML. Together they defuse the classic attack of uploading an HTML file and having your domain serve it as a page.

Remembering the type

The hash name carries no type, so the service has to remember what the client declared. A small JSON file alongside the data does it.

meta.jsJavaScript
import { readFile, writeFile } from "node:fs/promises";

const META = new URL("./meta.json", import.meta.url);
let table = {};

try {
  table = JSON.parse(await readFile(META, "utf8"));
} catch (err) {
  if (err.code !== "ENOENT") throw err;
}

export function remember(id, type) {
  table[id] = type;
  return writeFile(META, JSON.stringify(table));
}

export function typeFor(id) {
  return table[id];
}

For a service with many files you would use a database, but this keeps the example dependency-free. Note that the stored type is what the client claimed. A client can send a text file with the header image/png. If the type matters for your product, sniff the first bytes against the known signatures, for example the eight-byte PNG header, before accepting the file.

The server

server.jsJavaScript
import { createServer } from "node:http";
import { handleUpload } from "./upload.js";
import { handleDownload } from "./download.js";
import { remember, typeFor } from "./meta.js";

createServer(async (req, res) => {
  try {
    if (req.method === "POST" && req.url === "/files") {
      const result = await handleUpload(req);
      await remember(result.id, result.type);
      res.writeHead(201, { "content-type": "application/json" });
      return res.end(JSON.stringify(result));
    }
    const match = req.url.match(/^\/files\/([^/?]+)$/);
    if (req.method === "GET" && match) {
      return await handleDownload(match[1], res, typeFor);
    }
    res.writeHead(404);
    res.end();
  } catch (err) {
    if (res.headersSent) return res.destroy();
    res.writeHead(err.status ?? 500, { "content-type": "application/json" });
    res.end(JSON.stringify({ error: err.status ? err.message : "server error" }));
  }
}).listen(3000, () => console.log("listening on 3000"));

The headersSent check protects a download that fails midway: once headers are out you cannot send a new status, so the only honest move is to destroy the socket and let the client see an incomplete transfer.

Trying it

Shell
echo "hello upload" > note.txt
curl -s -X POST localhost:3000/files -H 'content-type: text/plain' --data-binary @note.txt
Text
{"id":"1b9d2f6a6e0b0d2f1d1c4e4bb8f35e8ddb1d5a0c8c3b9a6f2a7d0e1c4b5a6f78","size":13,"type":"text/plain"}

The size is 13 because the string and its newline are 13 bytes. The digest above is an illustrative value, and you will see the real SHA-256 of your file. Uploading the same file again returns the same id and does not create a second copy. Now the rejections.

Shell
curl -s -X POST localhost:3000/files -H 'content-type: application/x-sh' --data-binary @note.txt
head -c 11000000 /dev/zero | curl -s -X POST localhost:3000/files -H 'content-type: application/pdf' --data-binary @-
Text
{"error":"type application/x-sh not allowed"}
{"error":"file too large"}

What to add before production

Three gaps deserve attention. Authentication: anyone can upload, so tie uploads to a user and apply a per-user quota. Content scanning: an allowed type is still not a safe file, so scan uploads with an antivirus service if users share them with each other. And storage: a local disk is one machine. For several servers, stream the same pipeline into object storage such as S3 instead of createWriteStream, keeping the hashing and limit transforms exactly as they are. The structure carries over because everything is a stream.

Also add cleanup for tmp. A crash between create and rename leaves orphans, so a nightly job that deletes files older than an hour keeps the directory clean.

Failure modes to test on purpose

Upload code is easy to write and hard to trust until you have broken it. Three failures are worth simulating before you ship, and each one exercises a different line of the handler.

Kill the client midway. Start an upload of a large file with curl and press Ctrl+C after a second. The request stream emits an error, pipeline rejects, the catch block removes the temporary file and the files directory stays clean. List tmp afterwards. If a file remains, a stream is not wired into the pipeline, and you want to find that now.

Send a lying length. Declare a content-length of 100 bytes and send 20 MB, which you can do with a raw socket tool. Node.js itself enforces the declared length for the parser, but chunked uploads declare nothing, so send one with curl -H 'transfer-encoding: chunked' and confirm that the byte counter still stops it at the limit and returns 413.

Fill the disk. A full disk makes the write stream emit an error with the code ENOSPC. The same catch handles it, but you should map that code to a 507 or a 503 and alert someone, because it is an operational failure and not a client mistake.

Concurrency deserves one more thought. Two clients uploading identical content at the same moment both write to different temporary names and both call rename onto the same final name. On the same filesystem, rename replaces the target atomically, and the content is identical, so the second one is harmless. That safety is a direct result of naming files by hash, and it is the reason this design needs no locks.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.