EthicsComputerCourses
Join training +91 90532 10052

File Uploads & Storage

Next.js Full Stack · Lesson 12 of 20 Intermediate 11 min read Updated

By the end of this lesson an EventHub organiser can upload a cover image for their meetup. You will receive the file in a Server Action, check its size and its real type, store it under a name you choose, save only that name in PostgreSQL, and serve it safely. In development the files go to a folder on your computer; in production the same code writes to S3-compatible object storage.

What you should know first: Server Actions & Forms, Caching & Revalidation and UI with Tailwind CSS. The browser side of file inputs is in File Upload Controls, and object storage itself in S3 Object Storage. Versions checked on 16 November 2026: Next.js 16.4.6, @aws-sdk/client-s3 and @aws-sdk/s3-request-presigner 3.1169.0.

Where should uploaded files live?

Not in the database, and not in public/. A database is built for small rows, and backing up 2 MB images with every row makes it slow and expensive. The public/ folder belongs to your code. We tested it: with next start running, we added public/late-file.txt and requested it.

Output
GET /late-file.txt -> 404

The running server did not see a file added after it started. On many hosting platforms the disk is also wiped on every deployment, or is read-only. Uploads need their own home.

Think of a cloakroom at Pune railway station. You hand over your bag and get a token with a number the cloakroom chose. The register records only the token, not the bag. EventHub works the same way: the image goes to object storage, a service that keeps files ("objects") under names ("keys"), and PostgreSQL keeps only the key.

Step 1: A column for the key

Add one optional column to Event in prisma/schema.prisma:

Text
model Event {
  // ...existing fields
  coverKey String? // storage key such as covers/3f2a....webp, never a user's file name
}
Terminal
npx prisma migrate dev --name cover_image
npx prisma generate

The migration was one line of SQL: ALTER TABLE "Event" ADD COLUMN "coverKey" TEXT;. Add coverKey: true to summaryFields in lib/events.ts, and EventSummary gains the field everywhere.

Step 2: Check the real file type

The browser sends a file name and a type such as image/png. Both are just text that the user, or an attacker, controls. Renaming page.html to cover.png changes nothing inside the file. If your server stores it and later serves it, a browser might run its script.

Real files start with fixed bytes called magic numbers: every PNG begins with 89 50 4E 47, every JPEG with FF D8 FF. Create lib/image-check.ts. It has no server-only import, so the browser could use it too and tests can import it directly:

TypeScript
export const MAX_COVER_BYTES = 2 * 1024 * 1024; // 2 MB

export const allowedCoverTypes = { "image/jpeg": "jpg", "image/png": "png", "image/webp": "webp" } as const;
export type CoverType = keyof typeof allowedCoverTypes;

const startsWith = (bytes: Uint8Array, sig: number[], offset = 0) =>
  sig.every((value, i) => bytes[offset + i] === value);

// Look at the first bytes ("magic numbers"), not at the name or the browser's claim.
export function detectImageType(bytes: Uint8Array): CoverType | null {
  if (startsWith(bytes, [0xff, 0xd8, 0xff])) return "image/jpeg";
  if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png";
  // RIFF....WEBP
  if (startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) && startsWith(bytes, [0x57, 0x45, 0x42, 0x50], 8)) return "image/webp";
  return null;
}

export function checkCover(size: number, firstBytes: Uint8Array) {
  if (size === 0) return { ok: false, error: "Choose an image to upload." } as const;
  if (size > MAX_COVER_BYTES) return { ok: false, error: "The image must be 2 MB or smaller." } as const;
  const type = detectImageType(firstBytes);
  if (!type) return { ok: false, error: "Use a JPEG, PNG or WebP image." } as const;
  return { ok: true, type, ext: allowedCoverTypes[type] } as const;
}

SVG is left out on purpose. An SVG file is XML that can contain scripts, so it is unsafe to accept from users unless you clean it with a specialised tool.

Step 3: Storage with two drivers

Create lib/storage.ts with one small interface and two implementations:

TypeScript
import "server-only";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";

export interface FileStorage {
  put(key: string, body: Uint8Array, contentType: string): Promise<void>;
  publicUrl(key: string): string;
}

export const LOCAL_ROOT = path.join(process.cwd(), "storage"); // git-ignored

function localStorage(): FileStorage {
  return {
    async put(key, body) {
      const target = path.join(LOCAL_ROOT, key);
      await mkdir(path.dirname(target), { recursive: true });
      await writeFile(target, body);
    },
    publicUrl: (key) => `/files/${key}`,
  };
}

// AWS S3, Cloudflare R2, MinIO, DigitalOcean Spaces and other S3-compatible services
function s3Storage(): FileStorage {
  const client = new S3Client({
    region: process.env.S3_REGION ?? "auto",
    endpoint: process.env.S3_ENDPOINT, // leave unset for AWS S3 itself
    forcePathStyle: Boolean(process.env.S3_ENDPOINT),
    credentials: {
      accessKeyId: process.env.S3_ACCESS_KEY_ID!,
      secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
    },
  });
  return {
    async put(key, body, contentType) {
      await client.send(new PutObjectCommand({
        Bucket: process.env.S3_BUCKET, Key: key, Body: body,
        ContentType: contentType, CacheControl: "public, max-age=31536000, immutable",
      }));
    },
    publicUrl: (key) => `${process.env.S3_PUBLIC_URL}/${key}`,
  };
}

export const storage: FileStorage = process.env.S3_BUCKET ? s3Storage() : localStorage();

Install the SDK with npm install @aws-sdk/client-s3@3.1169.0, and add /storage to .gitignore. The rest of EventHub only ever calls storage.put and storage.publicUrl, so switching providers is a matter of environment variables. Add the names to .env.example with empty values: S3_BUCKET, S3_REGION, S3_ENDPOINT, S3_PUBLIC_URL, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY. In production, create an access key that may only write to this one bucket, never your main account key. Each provider prices storage and traffic differently; read their official pricing pages before you choose.

The same file also exports readLocalFile(key), which reads from storage/ and returns null if the file is missing.

Step 4: The uploadCover Server Action

Add this to app/events/actions.ts. It follows the same four steps as every EventHub action:

TypeScript
export async function uploadCover(_prev: CoverState, formData: FormData): Promise<CoverState> {
  const user = await requireUser(); // 1. who is asking?

  const slug = formData.get("slug");
  const file = formData.get("cover");
  if (typeof slug !== "string" || !(file instanceof File)) return { ok: false, message: "Choose an image to upload." };

  // 2. only the organiser may change this meetup's cover
  const event = await db.event.findFirst({ where: { slug, organiserId: user.id }, select: { id: true } });
  if (!event) return { ok: false, message: "Only the organiser can change the cover." };

  // 3. check size and real file type (the first bytes), never the name or file.type
  const bytes = new Uint8Array(await file.arrayBuffer());
  const check = checkCover(file.size, bytes.subarray(0, 12));
  if (!check.ok) return { ok: false, message: check.error };

  // 4. our own random name: no user text reaches the file system or the URL
  const key = `covers/${crypto.randomUUID()}.${check.ext}`;
  await storage.put(key, bytes, check.type);
  await db.event.update({ where: { id: event.id }, data: { coverKey: key } });

  updateTag(`event:${slug}`);
  updateTag("events");
  return { ok: true, message: "Cover updated." };
}

Look at the order. The ownership check runs before reading the file, so a stranger cannot make the server do work. The key uses crypto.randomUUID(), so a file named ../../.env or rohtak meetup (final).png never touches a path or a URL. And updateTag expires the cached meetup page from the caching lesson, so the organiser sees the new cover at once.

The form, components/cover-upload.tsx, is a Client Component with <input type="file" name="cover" accept="image/jpeg,image/png,image/webp">, a hidden slug input and useActionState. Its onChange handler also checks file.size and disables the button for files over 2 MB, which saves a slow upload on a mobile connection. accept only filters the file picker; it is a convenience, not a check. The event page shows the form only when a new isOrganiser(slug, userId) function in lib/events.ts returns true, and shows the cover with next/image.

Step 5: The body size limit

We tried a real 1.5 MB PNG and the upload failed. The browser console said TypeError: Failed to fetch, and the server log explained:

Output
⨯ Error: Body exceeded 1 MB limit.
To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit
    at ignore-listed frames {
  statusCode: 413,
  digest: '1184005959'
}

Server Actions accept at most 1 MB by default, which protects the server from huge requests. Raise it just enough in next.config.ts:

TypeScript
const nextConfig: NextConfig = {
  // ...cacheComponents, typedRoutes and the rest as before
  experimental: {
    serverActions: {
      bodySizeLimit: "3mb", // 2 MB covers plus multipart overhead; the action still checks 2 MB
    },
  },
};

The limit counts the whole request, including the form's boundaries and the other fields, so leave some room above your own 2 MB rule. Keep both checks: the framework limit stops giant requests early, and checkCover enforces your real rule.

Step 6: Serve local files safely

Files in storage/ need a Route Handler. Create app/files/[...key]/route.ts. The [...key] folder is a catch-all segment, so /files/covers/abc.png gives key = ["covers", "abc.png"]:

TypeScript
import { readLocalFile } from "@/lib/storage";

const types: Record<string, string> = { jpg: "image/jpeg", png: "image/png", webp: "image/webp" };
// Only keys we create ourselves: covers/<uuid>.<ext>. This also blocks "../" tricks.
const validKey = /^covers\/[0-9a-f-]{36}\.(jpg|png|webp)$/;

export async function GET(_request: Request, ctx: RouteContext<"/files/[...key]">) {
  const key = (await ctx.params).key.join("/");
  if (process.env.S3_BUCKET || !validKey.test(key)) return new Response("Not found", { status: 404 });

  const file = await readLocalFile(key);
  if (!file) return new Response("Not found", { status: 404 });

  return new Response(new Uint8Array(file), {
    headers: {
      "Content-Type": types[key.split(".").pop()!],
      "X-Content-Type-Options": "nosniff",
      "Cache-Control": "public, max-age=31536000, immutable",
    },
  });
}

X-Content-Type-Options: nosniff tells browsers to trust the Content-Type and never guess. The long cache time is safe because a key is never reused: a new cover always gets a new random name.

Step 7: Run it

Signed in as Ananya, the organiser of the Rohtak meetup, we drove Chrome through three uploads, then checked the file route and a visitor's view:

Output
fake.png (HTML inside)      -> "Use a JPEG, PNG or WebP image."
big-1.5mb.png               -> "Cover updated."
rohtak-cover.png (29 KB)    -> "Cover updated."
huge-2.6mb.png              -> button disabled: "The image must be 2 MB or smaller."
img src: /_next/image?url=%2Ffiles%2Fcovers%2F1277e497-0b77-434f-94f2-080c13894f30.png&w=3840&q=75

HEAD /files/covers/1277e497-....png -> 200, content-type: image/png, x-content-type-options: nosniff
GET  /files/../.env                 -> 404
Meera (not the organiser) sees the upload form: no

The <img> points at the Next.js image optimiser, which fetched the original from /files/... and served a resized copy. With S3 storage, publicUrl returns the bucket's address instead, and you must list that host in images.remotePatterns in next.config.ts before next/image will load it.

Large files: upload straight to storage

Every byte of a Server Action upload passes through your Next.js server. For 2 MB covers that is fine. For videos or PDFs, the Next.js docs suggest uploading from the browser directly to storage. The server creates a presigned URL: a storage address with a time-limited signature that allows exactly one action, such as "PUT this key". Signing happens locally, so this script ran with AWS's published example keys and no network:

TypeScript
const client = new S3Client({
  region: "ap-south-1",
  requestChecksumCalculation: "WHEN_REQUIRED", // do not sign a checksum of an empty body
  credentials: { accessKeyId: "AKIAIOSFODNN7EXAMPLE", secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" },
});
const url = await getSignedUrl(
  client,
  new PutObjectCommand({ Bucket: "eventhub-covers", Key: "covers/3f2a9c1e-demo.webp", ContentType: "image/webp" }),
  { expiresIn: 300 }, // 5 minutes
);
Output
https://eventhub-covers.s3.ap-south-1.amazonaws.com/covers/3f2a9c1e-demo.webp
  X-Amz-Algorithm = AWS4-HMAC-SHA256
  X-Amz-Credential = AKIAIOSFODNN7EXAMPLE/20261116/ap-south-1/s3/aws4_request
  X-Amz-Expires = 300
  X-Amz-Signature = 5c315cb31f545119...
  X-Amz-SignedHeaders = host
  x-id = PutObject

We trimmed two lines. Without the requestChecksumCalculation line, this SDK version also added x-amz-checksum-crc32=AAAAAA== to the URL, a checksum of an empty body, which would not match a real file. The server still decides the key and checks ownership before signing, and after the upload it should check the stored object's size and first bytes before saving the key.

Try it: magic numbers

This is detectImageType from Step 2. It checks three sample byte arrays, and you can pick your own file to test it:

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

const startsWith = (bytes, sig, offset = 0) => sig.every((value, i) => bytes[offset + i] === value);
function detectImageType(bytes) {
  if (startsWith(bytes, [0xff, 0xd8, 0xff])) return "image/jpeg";
  if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png";
  if (startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) && startsWith(bytes, [0x57, 0x45, 0x42, 0x50], 8)) return "image/webp";
  return null;
}
const hex = (bytes) => [...bytes.slice(0, 12)].map((b) => b.toString(16).padStart(2, "0")).join(" ");

const samples = [
  ["photo.jpg", new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01])],
  ["banner.webp", new TextEncoder().encode("RIFF\x24\x00\x00\x00WEBPVP8 ")],
  ["cover.png (really HTML)", new TextEncoder().encode("<html><script>alert(1)</script>")],
];
for (const [name, bytes] of samples) console.log(name.padEnd(24), hex(bytes), "->", detectImageType(bytes) ?? "rejected");

function Checker() {
  const [result, setResult] = useState("Pick a file");
  async function check(file) {
    const bytes = new Uint8Array(await file.slice(0, 12).arrayBuffer());
    setResult(`${file.name} (browser says "${file.type}"): ${detectImageType(bytes) ?? "rejected"}`);
  }
  return (
    <p>
      <input type="file" onChange={(e) => e.target.files[0] && check(e.target.files[0])} />
      <br />{result}
    </p>
  );
}
createRoot(document.getElementById("root")).render(<Checker />);
Output
photo.jpg                ff d8 ff e0 00 10 4a 46 49 46 00 01 -> image/jpeg
banner.webp              52 49 46 46 24 00 00 00 57 45 42 50 -> image/webp
cover.png (really HTML)  3c 68 74 6d 6c 3e 3c 73 63 72 69 70 -> rejected

Rename a text file to .png and pick it: the browser reports image/png, and the checker still rejects it. file.slice(0, 12) reads only twelve bytes, however large the file is.

Common mistakes

  • Trusting file.type or the file name. Both come from the client. Check the first bytes.
  • Using the uploaded name as the storage key. It invites path tricks and clashes. Generate a random key.
  • Saving uploads in public/. The running server may not serve new files, and deployments can wipe them.
  • Forgetting the ownership check. Hiding the form is not security; the action checks organiserId itself.
  • Accepting SVG from users. It can carry scripts. Allow raster formats only.

Interview questions

1. Why store uploaded files in object storage instead of the database?

Databases are tuned for small, structured rows; large binary data makes backups, replication and queries slower and costlier. Object storage is cheap per gigabyte, serves files directly or through a CDN, and scales separately. The database keeps only the key and metadata.

2. How do you check that an uploaded file is really an image?

Read the first bytes and compare them with known signatures, such as FF D8 FF for JPEG. The file name and the Content-Type sent by the browser are user input and can lie. Also enforce a maximum size, use an allow-list of formats and serve files with X-Content-Type-Options: nosniff.

3. What is a presigned URL?

A storage URL that carries a signature, created with the server's secret, which allows one operation on one key until it expires. The browser can upload directly to storage without ever seeing the secret, which saves the app server's bandwidth for large files.

4. Why does a Next.js Server Action reject a 1.5 MB upload by default?

Server Actions have a 1 MB body limit to protect the server from oversized requests. You raise it with experimental.serverActions.bodySizeLimit in next.config.ts, slightly above your own maximum, and still validate the size in the action.

Key points

  • Uploaded files go to object storage; PostgreSQL stores only a key such as covers/<uuid>.png.
  • Check size and magic bytes on the server; accept and client checks are only for convenience.
  • Generate random keys; never put user file names into paths or URLs.
  • One FileStorage interface with a local driver for development and an S3-compatible driver for production, chosen by environment variables.
  • Server Actions accept 1 MB by default; set bodySizeLimit with room for overhead.
  • Serve files with the right Content-Type, nosniff and long caching for never-reused keys; use presigned URLs for large direct uploads.

Exercise

When an organiser uploads a new cover, the old file stays in storage forever. Add a remove(key) method to the FileStorage interface (local: delete the file; S3: DeleteObjectCommand). In uploadCover, read the old coverKey together with the ownership check, and delete the old file only after the database update has succeeded. Explain why the order matters.

Show solution
TypeScript
// lib/storage.ts (local driver)
async remove(key) {
  await rm(path.join(LOCAL_ROOT, key), { force: true }); // rm from node:fs/promises
},
// S3 driver
async remove(key) {
  await client.send(new DeleteObjectCommand({ Bucket: process.env.S3_BUCKET, Key: key }));
},

// app/events/actions.ts, inside uploadCover
const event = await db.event.findFirst({
  where: { slug, organiserId: user.id },
  select: { id: true, coverKey: true },
});
// ...checks and storage.put(key, ...) as before
await db.event.update({ where: { id: event.id }, data: { coverKey: key } });
if (event.coverKey) await storage.remove(event.coverKey).catch(() => {}); // best effort

If you deleted the old file first and the database update then failed, the meetup would point at a missing image. Deleting last means the worst case is one orphaned file, which a cleanup job can remove later. The old key comes from the database, never from the form, so a user cannot make the server delete someone else's file.

Quick Quiz

1. An attacker renames page.html to cover.png. Which check catches it?

2. Why does EventHub store the cover as covers/<uuid>.png?

3. What happened when a 1.5 MB file was sent to the Server Action with default settings?

4. What does X-Content-Type-Options: nosniff do on the file route?

Learn Next.js Full Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call