Skip to content

No. 32Backend8 min read2,169 words

How to handle file uploads safely: in Node and Next.js

How to handle file uploads safely in Node and Next.js: validate real file bytes, cap size, upload direct to storage with presigned URLs, and serve files safely.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways ยท 05

The short version

  1. 01Never trust the client's filename or Content-Type header: detect the real type from the file's magic bytes, check it against an allowlist, and generate your own storage name.
  2. 02Enforce size limits at every layer, including the parser that counts bytes as they stream in, because the Content-Length header can lie.
  3. 03For anything larger than small images, have the browser upload straight to object storage with a short-lived presigned URL or POST policy, so file bytes never pass through your app server.
  4. 04Do not mark an upload as complete when you issue the URL; verify the object exists, check its real size and type server side, then flip the database row from pending to ready.
  5. 05Serve user files from a separate domain with X-Content-Type-Options: nosniff, and Content-Disposition: attachment for anything you have not verified, so an uploaded HTML or SVG file cannot run script as your site.
On this page ยท 10

To handle file uploads safely, treat everything the client sends as hostile: detect the real file type from its bytes, enforce size limits while the data streams in, generate your own file names, upload large files directly to object storage with short-lived presigned URLs, verify the upload server side before trusting it, and serve files from a separate origin that cannot run code as your app. Each step is simple. Skipping any one of them is how a tidy upload feature becomes an incident.

File uploads look done after an afternoon and then quietly become the worst part of a codebase six months later. The happy path is easy. The problem is everything around it: lying clients, oversized files, malicious payloads, and the slow realisation that you are now running a free file host for strangers. The OWASP File Upload Cheat Sheet is the canonical reference; this is how we apply it in Node and Next.js apps.

What can go wrong with file uploads

It helps to know what you are defending against before picking defences:

ThreatWhat it looks likeDefence
Type spoofingA script labelled image/png, or invoice.pdf.exeDetect type from bytes; allowlist
Path traversalA filename like ../../config.jsonNever use the client's filename for storage
Resource exhaustionA multi-gigabyte upload, or millions of tiny onesSize limits at every layer; rate limits per user
Stored cross-site scriptingUploaded HTML or SVG served from your domain runs scriptSeparate origin, nosniff, attachment disposition
Decompression bombsA small archive or image that expands enormously when processedLimit decompressed size and image pixel dimensions
Malware distributionYour bucket used to host and share malicious filesScanning, private buckets, signed download URLs
Data leakagePrivate documents in a public bucket with guessable keysPrivate by default; short-lived signed URLs
Abandoned uploads and costOrphaned objects piling upPending status, cleanup jobs, lifecycle rules

Never trust the filename or the content type

The first rule is that everything the browser sends is a suggestion, not a fact. The Content-Type header is set by the client and can say image/png for a script. The filename can contain path segments, or a Unicode trick that renders as invoice.pdf but ends in .exe. Treat all of it as hostile input, the same mindset you bring to any other user input.

Validate the actual bytes. Most formats start with a recognisable signature, the magic number: a real PNG starts with 89 50 4E 47, a JPEG with FF D8 FF, a PDF with %PDF. The file-type library does this detection for you and is worth the dependency:

import { fileTypeFromBuffer } from "file-type";
 
const ALLOWED = new Set(["image/png", "image/jpeg", "image/webp"]);
const MAX_BYTES = 5 * 1024 * 1024; // 5 MB
 
export async function validateImage(buffer: Uint8Array) {
  if (buffer.byteLength > MAX_BYTES) {
    throw new Error("File too large");
  }
 
  const detected = await fileTypeFromBuffer(buffer);
  if (!detected || !ALLOWED.has(detected.mime)) {
    throw new Error("Unsupported file type");
  }
 
  return detected; // e.g. { ext: "png", mime: "image/png" }
}

Use an allowlist, never a blocklist. "Images and PDFs" is a policy you can enforce. "Anything except executables" is not, because the list of dangerous types is longer than you think and keeps growing.

Derive the extension from the detected type, not from the name the user gave you, and generate your own name. A UUID plus the verified extension kills path traversal and collisions in one move. If you need the original name for display, store it as a separate, sanitised metadata field and never use it to build a path.

import { randomUUID } from "node:crypto";
 
const detected = await validateImage(bytes);
const storageKey = `uploads/${randomUUID()}.${detected.ext}`;

Re-encode images you accept

Magic-byte detection proves a file starts like a PNG. It does not prove the rest of the file is harmless: polyglot files can be valid images and something else at the same time. For user images, decode and re-encode them with an image library such as sharp. That normalises the format, lets you cap pixel dimensions (a defence against decompression bombs), and strips metadata like EXIF GPS coordinates that users often do not realise they are sharing. You will want resized variants anyway, as covered in our image optimisation guide.

Set size limits before the bytes hit your server

Validation only helps if the request reaches your handler in one piece. Without a cap, someone can stream a huge file and exhaust memory or disk while you wait. Set the limit at every layer that has one:

  1. Platform and proxy. Hosting platforms cap function request bodies (Vercel documents its limits in function limitations), and reverse proxies like nginx have their own setting.
  2. Framework. Next.js Server Actions accept 1MB request bodies by default, configurable with serverActions.bodySizeLimit. Keep it low unless you have a reason.
  3. Parser. If you parse multipart yourself with busboy or multer, set limits explicitly rather than trusting defaults.
  4. Application. Check the size again after parsing, per file type, since a 5 MB limit for avatars and a 50 MB limit for documents are both reasonable.
import multer from "multer";
 
export const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024,
    files: 1,
    fields: 10,
  },
});

The Content-Length header can also lie, so the parser limit is the one that actually protects you: it counts bytes as they arrive and aborts mid-stream. A header check is just a cheap early reject for honest clients.

In a Next.js route handler, await req.formData() buffers the whole body in memory. That is fine for a small avatar behind a platform limit. It is the wrong tool for large files, which brings us to the better pattern.

Upload straight to storage with presigned URLs

For anything beyond small images, do not route file bytes through your application server at all. Have the browser upload directly to object storage (S3, R2, GCS) using a presigned URL your backend generates. Your server stays in the control path, deciding who can upload and what key they get, but never touches the payload. AWS documents the pattern in uploading objects with presigned URLs, and Cloudflare R2 supports the same S3 API.

The flow:

  1. The client asks your API for permission to upload, stating the type and size.
  2. Your API checks auth, quota and the requested type and size, creates a pending row, and returns a short-lived signed URL or form policy.
  3. The browser uploads directly to storage.
  4. Your API verifies the object and marks the row ready.

Use a POST policy to enforce size

A plain presigned PUT can lock the key and content type, but it does not bound the body size. A presigned POST with a policy document can, using a content-length-range condition, so storage itself rejects oversized files. The AWS SDK's @aws-sdk/s3-presigned-post package generates the URL, form fields and signed policy for you:

import { S3Client } from "@aws-sdk/client-s3";
import { createPresignedPost } from "@aws-sdk/s3-presigned-post";
import { randomUUID } from "node:crypto";
 
const s3 = new S3Client({ region: process.env.AWS_REGION });
 
const TYPES: Record<string, string> = { "image/png": "png", "image/jpeg": "jpg", "application/pdf": "pdf" };
const MAX_BYTES = 20 * 1024 * 1024;
 
export async function createUpload(userId: string, contentType: string) {
  const ext = TYPES[contentType];
  if (!ext) throw new Error("Unsupported type");
 
  const key = `users/${userId}/${randomUUID()}.${ext}`;
 
  const { url, fields } = await createPresignedPost(s3, {
    Bucket: process.env.UPLOAD_BUCKET!,
    Key: key,
    Conditions: [
      ["content-length-range", 1, MAX_BYTES],
      ["eq", "$Content-Type", contentType],
    ],
    Fields: { "Content-Type": contentType },
    Expires: 60, // seconds
  });
 
  // Insert an uploads row with status 'pending' here
  return { url, fields, key };
}

The browser sends a multipart form to url with the returned fields plus the file. On Vercel Blob, the equivalent is a client upload token with maximumSizeInBytes and allowedContentTypes, which gives you similar guarantees with less ceremony.

Verify before you trust

The step people forget: do not mark an upload as done because you handed out a URL. The client may have failed, uploaded something else, or never called storage at all. Confirm it server side, either when the client calls back after uploading or from a bucket event notification:

  • Check the object exists and its real size matches your limit.
  • Read the first bytes and re-run magic-number detection, since the declared content type is still just a declaration.
  • Kick off processing, re-encoding and scanning in a background job, and only then mark it ready.

A clean pattern is to upload into a quarantine prefix or bucket and move objects to the serving location only after they pass checks.

Store metadata, not blobs, in your database

Keep files in object storage and a record in Postgres. The record is what your app queries and authorises against; the bytes live somewhere cheap and scalable. A reasonable shape:

CREATE TABLE uploads (
  id             uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id        uuid NOT NULL REFERENCES users(id),
  storage_key    text NOT NULL UNIQUE,
  original_name  text,
  mime_type      text NOT NULL,
  size_bytes     bigint NOT NULL,
  status         text NOT NULL DEFAULT 'pending', -- pending | ready | rejected
  created_at     timestamptz NOT NULL DEFAULT now()
);
 
CREATE INDEX uploads_pending_idx ON uploads (created_at) WHERE status = 'pending';

Rows start as pending when you issue the upload URL and flip to ready only after verification. A scheduled job sweeps pending rows older than an hour and deletes both the row and any object, so abandoned uploads do not pile up. Storage lifecycle rules on the quarantine prefix are a good second net. Store the verified mime_type and size_bytes from your own checks, not the client's claims, so later code can trust them.

Scan what other people will open

If files uploaded by one user are downloaded by others, or opened by your staff, add malware scanning. Open-source engines like ClamAV and managed scanning services both work; run the scan asynchronously in the verification job, keep the file in pending until it passes, and reject or quarantine anything flagged. Archives deserve extra suspicion: if you extract them, cap the total uncompressed size and file count, and never extract to paths built from names inside the archive.

For uploads containing sensitive personal data, such as medical or identity documents, scanning is only part of the job; encryption, access logging and retention rules matter too. Our guide to building HIPAA-conscious software covers that side, and claim photos and policy documents raise the same questions in insurance software.

Serve files without becoming an open door

How you serve files back is its own security surface.

Use a separate origin. If an attacker uploads an HTML or SVG file with a script in it and you serve it from your main domain, that script runs as your site, with access to your users' sessions. Serve uploads from a separate domain, such as a dedicated storage or CDN hostname, that holds no cookies for your app.

Stop the browser guessing. Send an accurate Content-Type and X-Content-Type-Options: nosniff so browsers do not reinterpret a file as something executable. For anything that is not a verified image, send Content-Disposition: attachment so it downloads rather than renders.

Keep private files private. Generate short-lived signed download URLs after checking the requester may see the file. Do not make the bucket public and rely on unguessable keys. IDs leak through logs, referrer headers and forwarded links, and "secret URL" is not access control.

Treat all of this as one part of a broader web application security checklist, not the whole job.

A file upload security checklist

  • Allowlist file types and detect them from bytes, not headers or extensions.
  • Generate storage names yourself; keep the original name as display-only metadata.
  • Limit size at the platform, framework, parser and application layers.
  • Upload large files directly to storage with short-lived presigned URLs or POST policies.
  • Verify each upload server side before marking it ready.
  • Re-encode images and strip metadata; cap pixel dimensions.
  • Scan files that other people will open.
  • Rate limit upload endpoints per user and track storage quotas.
  • Serve from a separate origin with nosniff, and attachment disposition for anything unverified.
  • Keep buckets private and use signed download URLs for private files.
  • Clean up abandoned uploads with a scheduled job and lifecycle rules.

Upload features you will not regret

Handling file uploads safely comes down to a short list: verify bytes instead of headers, cap size at every layer, push large payloads straight to storage, confirm uploads server side before trusting them, and serve files from an origin that cannot run code as your app. None of it is hard on its own, and all of it is much cheaper to build in than to retrofit after an incident.

Upload pipelines, document handling and media processing are part of our API and backend engineering work. If your current upload flow trusts the client more than you would like, get in touch and we will walk through it with you.

Pair this with the right response headers; our security headers checklist gives safe starting values.

FAQ ยท 05 questions

Frequently asked questions

How do I validate the file type of an upload?

Read the first bytes of the file and match them against known signatures, often called magic numbers. A PNG starts with the bytes 89 50 4E 47, for example. Libraries such as file-type for Node do this reliably. Check the detected type against a short allowlist and ignore both the file extension and the Content-Type header the browser sent.

What is a presigned URL for uploads?

A presigned URL is a temporary, signed link your server generates that lets one client upload one object directly to storage such as Amazon S3 or Cloudflare R2. It expires after a short time and can be restricted to a specific key and content type. Your server decides who may upload, but the file bytes go straight to storage.

Are SVG uploads safe?

Not by default. SVG is an XML format that can contain script, so serving a user-uploaded SVG inline from your main domain can lead to cross-site scripting. Either reject SVG, sanitise it with a dedicated library, convert it to a raster image, or serve it only from an isolated domain with Content-Disposition: attachment.

Do I need to virus scan uploaded files?

If uploaded files are downloaded or opened by other users or your staff, scanning is a sensible layer, especially for documents and archives. Run it asynchronously in a background job and keep the file in a pending state until the scan passes. Scanning complements, rather than replaces, type validation and safe serving.

What is the maximum upload size for Next.js?

Server Actions accept request bodies up to 1MB by default, configurable with serverActions.bodySizeLimit in next.config. Route handlers have no Next.js-specific cap, but your hosting platform usually limits function request bodies, and buffering large files in memory is risky anyway. For large files, upload directly to object storage instead.

Filed underBackendSecurity

Related service

API & Backend Engineering

Secure, well-documented APIs that scale.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1โ€“2 weeks
Pricing
Fixed price per phase
You own
All code and accounts