Next.jsMedium

How do you handle file uploads in Next.js?

For small files, send multipart/form-data to a Server Function or Route Handler and read the File from formData(), then store it in object storage. For large files, upload directly from the browser to storage (S3, R2, Vercel Blob) using a presigned URL that your server issues, so the file never passes through your Next.js server.

Small uploads through the server

  1. A <form> with <input type="file" name="avatar"> and action={uploadAction} (Server Function), or fetch to a Route Handler with a FormData body.
  2. On the server: const file = formData.get("avatar") as File.
  3. Validate size and type (file.size, file.type, and ideally the magic bytes).
  4. Read await file.arrayBuffer() or stream file.stream() to storage.

Server Functions have a 1MB body limit by default; raise it with serverActions.bodySizeLimit in next.config.ts. Hosting platforms also cap request bodies (for example around 4.5MB on Vercel Functions).

Large uploads: presigned URLs

  1. The client asks a Route Handler for an upload URL (after auth).
  2. The server creates a short-lived presigned PUT URL, restricted by key, type and size.
  3. The browser uploads directly to storage and shows progress.
  4. The client tells the server the upload finished, and the server records it.

Do not

  • Write uploads to the local disk or public/ on serverless hosts. The file system is ephemeral and public/ is only read at build time.
  • Trust the file name or extension; generate your own keys.
  • Serve uploaded HTML or SVG from your main domain without sanitizing (XSS risk).

Code example

tsx
1// app/profile/actions.ts
2"use server";
3
4import { put } from "@vercel/blob"; // or S3/R2 SDK
5import { updateTag } from "next/cache";
6import { verifySession } from "@/lib/dal";
7import { db } from "@/lib/db";
8
9const MAX = 2 * 1024 * 1024; // 2MB (set serverActions.bodySizeLimit: "3mb")
10const TYPES = ["image/png", "image/jpeg", "image/webp"];
11
12export async function uploadAvatar(_prev: { error?: string }, formData: FormData) {
13 const session = await verifySession();
14 if (!session) return { error: "Please sign in" };
15
16 const file = formData.get("avatar");
17 if (!(file instanceof File) || file.size === 0) return { error: "Choose a file" };
18 if (file.size > MAX) return { error: "Max 2MB" };
19 if (!TYPES.includes(file.type)) return { error: "PNG, JPEG or WebP only" };
20
21 const blob = await put(`avatars/${session.userId}-${crypto.randomUUID()}`, file, { access: "public" });
22 await db.user.update({ where: { id: session.userId }, data: { avatarUrl: blob.url } });
23 updateTag(`user:${session.userId}`);
24 return {};
25}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app