How-To Guide

How to Secure File Uploads in a Web API

Harden a multipart upload endpoint with size limits, magic-byte type checks, path containment, safe storage names, and malware scanning before serving.

On this page

  1. Introduction
  2. Validate the upload at every layer
  3. Enforce size and stream limits
  4. Verify content type by inspecting bytes
  5. Store outside the web root and rename
  6. Prevent path traversal and overwrites
  7. Scan for malware and serve safely
  8. Handle errors and clean up
  9. Testing secure uploads
  10. Common pitfalls
  11. Conclusion

Introduction

A file upload endpoint is one of the riskiest surfaces in a web API because it accepts attacker-controlled bytes and then writes them somewhere. The classic failures are well known: an uploaded script that executes because it landed in the web root, a path-traversal filename that overwrites a configuration file, an oversized body that exhausts disk, a spoofed Content-Type that bypasses validation, and malware redistributed to other users. Every one of these comes from trusting something the client controls.

This tutorial builds a hardened multipart upload endpoint. It covers layered validation, size and stream limits, magic-byte type verification, path containment, safe storage naming, scanning, and safe serving. The examples use TypeScript, but the defenses are protocol-level and apply to any stack.

Validate the upload at every layer

Security comes from defense in depth: several independent checks, each of which could fail without exposing the system. The layers are the reverse proxy, the framework body limit, the application validator, the storage layer, and the serving layer. A check that lives only in the application is bypassed the moment someone deploys a second path to the same storage. Put the size limit at the proxy and the framework as well as in the code, because the cheapest rejection is the one that never allocates memory.

Define explicitly what an upload is allowed to be before writing any handler: the maximum size, the allowed formats, whether the content is public or private, and who may download the result. A handler that starts from “accept any file” cannot be retrofitted into a safe one; start from a strict allowlist.

Enforce size and stream limits

A multipart parser that buffers the whole body in memory turns a 5 GB upload into an out-of-memory kill. Parse as a stream, count bytes as they arrive, and abort the request the moment the limit is exceeded. The framework limit is a coarse guard; the streaming counter is the exact one, because Content-Length may be absent (chunked transfer) or lying (it does not bound the actual bytes if the client keeps sending).

import { pipeline } from 'node:stream/promises';
import { createWriteStream } from 'node:fs';
import type { Readable } from 'node:stream';

const MAX_BYTES = 10 * 1024 * 1024; // 10 MiB

async function persist(stream: Readable, destPath: string): Promise<number> {
  let seen = 0;
  const counter = new (await import('node:stream')).Transform({
    transform(chunk, _enc, cb) {
      seen += chunk.length;
      if (seen > MAX_BYTES) {
        cb(new Error('upload_too_large'));
        return;
      }
      cb(null, chunk);
    },
  });
  // If the write or the parser throws, pipeline destroys both streams.
  await pipeline(stream, counter, createWriteStream(destPath, { flags: 'wx' }));
  return seen;
}

Fail on truncation as well. A client that disconnects mid-upload leaves a partial file; treat a short read as a corrupt upload and delete it, rather than storing a half file that later passes a size check.

Verify content type by inspecting bytes

The Content-Type header and the filename extension are hints, not facts. Confirm the format from the file’s magic bytes. A JPEG starts with FF D8 FF, a PNG with 89 50 4E 47, a PDF with %PDF-. Read the first bytes of the stored file and compare against the expected signature for the claimed type; reject a mismatch. Then, for formats the browser renders, prefer re-encoding: decoding an image and writing a fresh PNG strips EXIF, embedded scripts, and malformed structure that a parser-based attack relies on.

# Inspect magic bytes on the server before accepting an upload.
head -c 8 upload.bin | xxd
# 89 50 4e 47 0d 0a 1a 0a  -> PNG
# ff d8 ff e0 00 10 4a 46  -> JPEG (JFIF segment)

# Re-encode an image to drop metadata and embedded payloads.
sharp input.jpg --strip --output cleaned.jpg

Content sniffing is not enough on its own either: a polyglot file can be a valid image and a valid script. The defenses that matter are that the file never executes and is never served from your origin as active content. Treat every stored file as untrusted data, not as a program.

Store outside the web root and rename

The stored file must not be reachable by URL directly from the web server, because a file that the server serves by extension can be executed or rendered. Store uploads in a dedicated directory or object store, and never under a path the static file handler maps. Generate the stored name yourself: a random UUID plus a validated extension, or a hash of the content. Never use the client’s filename as the on-disk name.

import { randomUUID } from 'node:crypto';
import { extname, resolve, sep } from 'node:path';

const UPLOAD_ROOT = resolve('/srv/uploads');

function safeStoredPath(originalName: string): string {
  const ext = extname(originalName).toLowerCase();
  const allowed = new Set(['.png', '.jpg', '.jpeg', '.pdf']);
  if (!allowed.has(ext)) throw new Error('unsupported_extension');

  const stored = `${randomUUID()}${ext}`;
  const dest = resolve(UPLOAD_ROOT, stored);
  // Containment check: the resolved path must stay inside the root.
  if (!dest.startsWith(UPLOAD_ROOT + sep)) throw new Error('path_traversal');
  return dest;
}

Compare the resolved path against the root using a separator-aware check, not a naive substring test: /srv/uploads-backup starts with /srv/uploads as a string but is a different directory. Keep the original filename only as metadata in the database, escaped as needed when displayed, so you never build a filesystem path from user input.

Prevent path traversal and overwrites

Path traversal is any filename that escapes the upload root via ../, an absolute path, or a platform-specific separator. The containment check above is the primary defense, but also reject filenames that contain a path separator at all, and normalize before validating. Overwrites are prevented by generating a unique name and by opening the destination with the exclusive flag wx, which fails if the path already exists. Without wx, a race between two uploads of the same generated name (or a pre-created symlink) can clobber or redirect the write. On Windows and case-insensitive filesystems, also reject names that differ only by case to avoid unexpected collisions.

Scan for malware and serve safely

If uploads are shared with other users or downloaded, scan them before they are made available. Scan on ingest, hold the file in a quarantine state until the scan passes, and on a positive result keep the file for investigation while marking it unavailable. Never scan-then-store in a way that lets a user download the file during the scan window.

Serving is where many implementations lose the gains from validation. Serve through a handler that sets Content-Disposition: attachment, a Content-Type you determined, and X-Content-Type-Options: nosniff, and serve the file from a separate origin or a signed URL so an HTML or SVG upload cannot run as script in your application’s origin. Never serve a user upload with an extension the server executes.

function sendDownload(res: Response, file: { path: string; mime: string; name: string }) {
  res.setHeader('Content-Type', file.mime);           // server-decided, not client-supplied
  res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}`);
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox");
  res.sendFile(file.path);
}

Handle errors and clean up

Fail closed: on any validation failure, delete the partial file and return a generic error. Do not echo the client filename or the server path in the error, because that leaks filesystem layout. Rate-limit uploads per account to bound abuse, and log the rejection reason (too large, bad type, traversal, scan failed) without logging file contents. Run a periodic job that deletes orphaned files that were never attached to a record and expired quarantine entries, so a failed upload path does not slowly fill the disk.

Testing secure uploads

Test the negative paths, not just the happy path. Assert that an oversized stream is aborted and nothing is written, that a file whose bytes do not match its claimed type is rejected, that a filename of ../../etc/passwd is contained or refused, and that the stored name is not the client-supplied one. Test that a download is sent with Content-Disposition: attachment and nosniff, and that a known test string in a quarantined file is not downloadable until the scan clears.

test('rejects a spoofed content type', async () => {
  // A shell script that claims to be an image.
  const body = Buffer.from('#!/bin/sh\necho pwned\n');
  const res = await upload({ filename: 'avatar.png', contentType: 'image/png', body });
  expect(res.status).toBe(415); // unsupported media type, bytes did not match
  expect(await filesIn(UPLOAD_ROOT)).toHaveLength(0); // nothing persisted
});

Common pitfalls

  • Trusting Content-Type or the extension. Both are client-controlled and spoofable.
  • Buffering the whole body. A large upload becomes an out-of-memory kill.
  • Storing inside the web root. A written file can be requested and executed.
  • Using the client filename on disk. It carries traversal and overwrite risk.
  • Naive prefix path checks. A sibling directory passes a string startsWith.
  • Serving without Content-Disposition. An HTML or SVG upload renders in your origin.
  • Validating only in the application. Proxy and framework layers must also limit size.

Conclusion

Securing uploads is a sequence of independent barriers: bound the size while streaming, confirm the real format from the bytes, generate the stored name and contain the path, keep files outside the web root and non-executable, scan untrusted content, and serve with attachment and nosniff from a separate origin. Each barrier assumes the previous one will fail, so a single missing check does not become a compromise. Test the rejection paths explicitly. An upload endpoint is safe when every input it accepts is constrained by something the client cannot influence.

Sources: OWASP File Upload Cheat Sheet, OWASP: Unrestricted File Upload, MDN: Content-Disposition.

FAQ

Is checking the file extension enough to validate an upload?
No. An extension and the client-supplied Content-Type are attacker-controlled and trivially spoofed. Inspect the file's magic bytes to confirm the real format, and for images decode and re-encode them so any embedded payload in metadata or malformed structure is discarded.
Where should uploaded files be stored?
Outside the web root, on a volume that is not executable, with a server-generated name. Serving the file through an application handler that sets Content-Disposition and a safe Content-Type prevents the browser from rendering attacker HTML or executing a script from your origin.
Do I still need antivirus scanning for user uploads?
Yes, if files are shared with other users or downloaded back. Scan on ingest, quarantine failures instead of deleting so you can investigate, and never trust a scan result from a client. For images and documents, a content-disarm approach plus scanning covers most vectors.

Related Examples