🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Next.js File Uploads: Validation, Storage, Progress

Next.js FeaturesđŸŸĸ Free Lesson

Next.js File Uploads: Validation, Storage, Progress

File uploads sit at the intersection of every hard part of web development: untrusted input, large payloads, slow networks, and storage costs. A Next.js application has two credible paths — a Server Action receiving FormData for simple flows, or a route handler coordinating a direct client-to-storage upload for anything big — and choosing the wrong one is how you end up with serverless functions timing out at four megabytes or with a progress bar that lies.

Getting uploads right also means deciding what happens after the bytes land: which storage class holds them, who may read them, how they are scanned, and how the application learns that processing finished. The pipeline below walks through parsing multipart bodies safely, validating type and size where it cannot be bypassed, streaming uploads to object storage, reporting honest progress, and adding virus scanning or image processing hooks without blocking the response. Each stage has a failure mode that only appears under real network conditions, and the lesson calls those out where they matter rather than leaving them for production to reveal.

Prerequisites

  • !Server Actions and route handlers
  • !Comfort with FormData and environment variables
  • !An S3-compatible bucket or blob storage account

What You'll Learn

  • 1Parse uploads via Server Action FormData and route handlers
  • 2Validate MIME type and size on the server even when the client checked
  • 3Stream files to S3-compatible storage with correct ACLs
  • 4Report upload progress accurately and handle failures gracefully

Two architectures, chosen by size

Small uploads — avatars, PDF attachments under a few megabytes — flow naturally through a Server Action. The browser posts multipart FormData, the action validates, and the server writes the file to storage. The platform's request body limit applies, which on typical serverless deployments is somewhere between one and four point five megabytes before you configure anything.

Large uploads need the client to talk to storage directly. The application issues a short-lived signed URL, the browser PUTs the file straight to S3 or the blob store, and a final callback action records the metadata. The Next.js server never touches the bytes, so function timeouts and body limits stop being relevant.

ConcernServer Action uploadSigned direct upload
Practical sizeUp to platform body limitHundreds of megabytes
Progress reportingIndeterminate unless proxiedReal, via fetch upload events
Server involvementParses and forwards bytesIssues URL, verifies result
Virus scanning hookInline before storageAsynchronous after callback
ComplexityLowModerate

Start with the action path and move a specific route to direct uploads when files outgrow the limit — not before.

A Server Action upload with real validation

Client-side accept attributes are a courtesy to users, not a security control. The server must independently verify the declared content type, sniff magic bytes when the stakes are high, and enforce a size ceiling before buffering the whole file into memory.

javascript
// app/profile/actions.js
'use server';

import { put } from '@vercel/blob';
import { revalidatePath } from 'next/cache';
import { getSession } from '@/lib/session';

const ALLOWED = new Map([
  ['image/jpeg', ['.jpg', '.jpeg']],
  ['image/png', ['.png']],
  ['image/webp', ['.webp']],
]);
const MAX_BYTES = 5 * 1024 * 1024;

export async function uploadAvatar(prevState, formData) {
  const session = await getSession();
  if (!session) {
    return { error: 'Sign in to change your avatar.' };
  }

  const file = formData.get('avatar');
  if (!file || typeof file === 'string') {
    return { error: 'Choose an image to upload.' };
  }

  if (file.size > MAX_BYTES) {
    return { error: 'Image must be 5 MB or smaller.' };
  }

  const ext = file.name.split('.').pop()?.toLowerCase();
  const allowedExts = ALLOWED.get(file.type);
  if (!allowedExts || !allowedExts.includes(`.${ext}`)) {
    return { error: 'Only JPEG, PNG, or WebP images are allowed.' };
  }

  const blob = await put(`avatars/${session.userId}-${Date.now()}.${ext}`, file, {
    access: 'public',
    contentType: file.type,
    addRandomSuffix: true,
  });

  await saveAvatarUrl(session.userId, blob.url);
  revalidatePath('/profile');

  return { success: true, url: blob.url };
}

addRandomSuffix or a timestamped key prevents two users overwriting each other and gives the CDN a stable cache key per version. Keeping the extension in the key while trusting only the sniffed content type balances human-readable buckets with correctness.

Direct uploads with signed URLs

When the file is too big for the function body limit, flip the flow: the client asks the server for permission and a URL, uploads itself, then confirms. The confirmation step is where you re-check the object's size and type so a client that skipped validation cannot register an oversized object as finished.

javascript
// app/uploads/actions.js
'use server';

import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
import { s3 } from '@/lib/s3-client';
import { getSession } from '@/lib/session';

const MAX_BYTES = 100 * 1024 * 1024;

export async function requestUpload(filename, contentType) {
  const session = await getSession();
  if (!session) {
    throw new Error('unauthorized');
  }

  if (!contentType.startsWith('video/')) {
    throw new Error('Only video uploads are supported here');
  }

  const key = `videos/${session.userId}/${crypto.randomUUID()}-${filename}`;

  const { url, fields } = await createPresignedPost(s3, {
    Bucket: process.env.UPLOAD_BUCKET,
    Key: key,
    Expires: 300,
    Conditions: [
      ['content-length-range', 0, MAX_BYTES],
      ['starts-with', '$Content-Type', 'video/'],
    ],
    Fields: { 'Content-Type': contentType },
  });

  return { url, fields, key };
}

export async function confirmUpload(key) {
  const session = await getSession();
  if (!session || !key.startsWith(`videos/${session.userId}/`)) {
    throw new Error('unauthorized');
  }
  await registerVideo(session.userId, key);
  return { ok: true };
}

The Conditions array is enforced by S3 itself, so the size ceiling holds even against a crafted client. The key prefix check in confirmUpload prevents one user from claiming another user's object.

// components/VideoDropzone.js
'use client';

import { useState } from 'react';
import { requestUpload, confirmUpload } from '../uploads/actions';

export function VideoDropzone() {
  const [status, setStatus] = useState('idle');
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState(null);

  async function handleFile(file) {
    setStatus('uploading');
    setError(null);
    setProgress(0);

    try {
      const { url, fields, key } = await requestUpload(file.name, file.type);

      const body = new FormData();
      Object.entries(fields).forEach(([k, v]) => body.append(k, v));
      body.append('file', file);

      await new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', url);
        xhr.upload.onprogress = (e) => {
          if (e.lengthComputable) {
            setProgress(Math.round((e.loaded / e.total) * 100));
          }
        };
        xhr.onload = () =>
          xhr.status >= 200 && xhr.status < 300
            ? resolve()
            : reject(new Error('Upload failed'));
        xhr.onerror = () => reject(new Error('Network error'));
        xhr.send(body);
      });

      await confirmUpload(key);
      setStatus('done');
    } catch (err) {
      setStatus('error');
      setError(err.message ?? 'Upload failed');
    }
  }

  if (status === 'done') {
    return <p role="status">Upload complete.</p>;
  }

  return (
    <div>
      <input
        type="file"
        accept="video/*"
        onChange={(e) => e.target.files?.[0] && handleFile(e.target.files[0])}
        disabled={status === 'uploading'}
      />
      {status === 'uploading' && (
        <progress value={progress} max="100">
          {progress}%
        </progress>
      )}
      {error && (
        <p role="alert">{error}</p>
      )}
    </div>
  );
}

XMLHttpRequest is not a legacy mistake here: the fetch upload-progress event is still unevenly supported, while XHR's upload.onprogress gives consistent numbers across browsers. The same routine should also catch HTTP error responses mid-transfer, because a silent network layer often reports success on a request the storage provider rejected — surface the status code in the per-file error state so a failed third file never looks complete.

Processing after the bytes land

Bytes in a bucket are not a finished feature. Generate thumbnails with an image pipeline, extract video metadata, and scan for malware before the object becomes publicly readable. The resilient pattern queues this work: the upload callback writes a pending row, a worker processes the object, and the UI polls or streams status. A synchronous sharp call inside the action works for small images but couples your function duration to image size, which is exactly the coupling direct uploads were meant to remove.

Multi-file queues, drag and drop, and resumable transfers

Real upload UIs almost never handle one file in isolation. Users drop a folder of product photos, lose connectivity halfway through the third one, and expect the interface to tell them exactly what happened. A queue component that tracks per-file state — pending, uploading with a percentage, processing, done, failed with a reason — turns an opaque spinner into something the user can trust. The queue itself is client state: an array of records keyed by a client-generated ID, updated by the same progress callbacks that drive the bar.

Drag and drop adds two behaviors worth implementing deliberately. The dragover handler must call preventDefault or the browser navigates away to open the file, which is the single most common bug in homemade dropzones. And the drop event's dataTransfer.files is the same File object the input produces, so one shared handleFile function serves both entry points — duplicating the logic is how the two paths drift apart.

For transfers measured in tens of megabytes or more, resumable protocols stop being optional. S3 multipart upload splits the object into parts, each with its own presigned URL; if the connection drops, the client lists the uploaded parts and re-sends only the missing ones instead of starting over. The application server stays out of the byte path and simply completes the multipart session when the client reports all parts present. On flaky mobile networks the difference between resume and restart is the difference between a user who finishes the upload and one who gives up after the second failure.

Failure modes worth designing for

Expired presigned URLs surface as confusing 403s when a user pauses mid-upload — extend expiry generously for big files. Retries after a dropped connection should reuse the same key when possible, or the storage bucket fills with orphaned parts; enable multipart cleanup on the bucket. And always delete the stored object when the associated database row is rejected, or you will pay for bytes nobody references.

Common Mistakes

Trusting the client's accept attribute as validation

Fix: Re-check content type and size in the action; the browser constraint is trivially bypassed.

Buffering huge files through a serverless function

Fix: Switch to presigned direct uploads once files approach the platform body limit.

Skipping the confirm step after a direct upload

Fix: Re-verify object size and type server-side before marking the record complete.

Showing a fake progress bar that jumps at the end

Fix: Use XHR upload progress or the storage provider's multipart progress callbacks for honest numbers.

Best Practices

  • Allowlist MIME types and extensions together on the server
  • Namespace object keys by user ID and enforce the prefix on confirmation
  • Process, scan, and transcode asynchronously after the upload completes
  • Set bucket lifecycle rules to clean up abandoned multipart uploads

Interview Questions

Q1: Why use XHR instead of fetch for upload progress?

The fetch UploadProgress event is not universally available; XMLHttpRequest's upload.onprogress provides reliable cross-browser percentages.

Q2: How do you enforce a size limit on direct uploads?

Include a content-length-range condition in the presigned POST policy so the storage provider rejects oversized bodies itself.

Q3: Where must file validation live?

On the server, in the action or confirmation handler — client-side checks are UX only and never a security boundary.

Key Takeaways

  • Small uploads fit a Server Action; large uploads need presigned direct-to-storage PUTs.
  • Validate type and size on the server every time, regardless of client checks.
  • Signed POST policies move the size ceiling enforcement into S3 itself.
  • Real progress comes from XHR upload events or multipart callbacks.
  • Post-upload processing and malware scanning belong in an async pipeline, not the request path.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement