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
- A
<form>with<input type="file" name="avatar">andaction={uploadAction}(Server Function), orfetchto a Route Handler with aFormDatabody. - On the server:
const file = formData.get("avatar") as File. - Validate size and type (
file.size,file.type, and ideally the magic bytes). - Read
await file.arrayBuffer()or streamfile.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
- The client asks a Route Handler for an upload URL (after auth).
- The server creates a short-lived presigned PUT URL, restricted by key, type and size.
- The browser uploads directly to storage and shows progress.
- 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 andpublic/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.ts2"use server";34import { put } from "@vercel/blob"; // or S3/R2 SDK5import { updateTag } from "next/cache";6import { verifySession } from "@/lib/dal";7import { db } from "@/lib/db";89const MAX = 2 * 1024 * 1024; // 2MB (set serverActions.bodySizeLimit: "3mb")10const TYPES = ["image/png", "image/jpeg", "image/webp"];1112export async function uploadAvatar(_prev: { error?: string }, formData: FormData) {13 const session = await verifySession();14 if (!session) return { error: "Please sign in" };1516 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" };2021 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.