Skip to the code

A brew photo upload that checks the file

Customers can add a photo of their brew to the gallery at Leaf and Kettle. Write the upload form's Server Action, uploadBrewPhoto(previous, formData), in app/actions.ts, for a form with useActionState. The form sends a file field, photo, and a text field, caption.

A file field arrives in FormData as a File, with a name, a size in bytes, a type, and its bytes, and all of it comes from the client: type is the browser's guess from the file's name, and a request sent by hand can say anything. Check, in this order, and return the first problem as { error }, saving nothing.

There's a photo: the field is a File with at least one byte. A file input left empty still sends a File, of size 0, and a hand-made request can send text instead. Otherwise: Choose a photo to upload.

It's at most 2 MB, 2 * 1024 * 1024 bytes: Photos can be up to 2 MB. Check size before reading any of the file. Next.js refuses Server Action requests over 1 MB unless experimental.serverActions.bodySizeLimit raises the limit, and the shop's next.config.ts sets it to "3mb", which leaves room for the rest of the form.

It's a JPEG, PNG, or WebP image: its type is image/jpeg, image/png, or image/webp, and its first bytes are that format's signature: FF D8 FF for JPEG, 89 50 4E 47 0D 0A 1A 0A for PNG, and for WebP the letters RIFF, four bytes of size, then WEBP. Otherwise: Upload a JPEG, PNG, or WebP photo.

The caption, trimmed, is at most 120 characters: Keep the caption to 120 characters.

Then save it with savePhoto({ name, type, size, caption, bytes }) from @/lib/photos. The name is <id>.<extension>, an id from newPhotoId() and jpg, png, or webp, never the name the file came with, and bytes is a Uint8Array of the whole file. Revalidate /gallery and return { error: null }.

photo: "../../my tea.png" (image/png, 4096 bytes, starts 89 50 4E 47 0D 0A 1A 0A)
caption: "  Morning sencha "
→ savePhoto({ name: "photo-1.png", type: "image/png", size: 4096, caption: "Morning sencha", bytes })
→ revalidatePath("/gallery") → { error: null }
 
photo: "notes.png" (image/png, starts "Steep for…") → { error: "Upload a JPEG, PNG, or WebP photo." }

The app's other files

lib/photos.ts, read-only. Import it as @/lib/photos.

export type Photo = { name: string; type: string; size: number; caption: string; bytes: Uint8Array };
 
/** Every photo saved: a stand-in for the shop's file storage. */
export const photos: Photo[] = [];
let count = 0;
 
/** A new id for a photo's file name, like "photo-1". */
export function newPhotoId(): string {
  count += 1;
  return `photo-${count}`;
}
 
export async function savePhoto(photo: Photo) {
  photos.push(photo);
}

What the tests check

  1. saves a PNG under a name the server makes, and revalidates the gallery
    const codes = (text) => [...text].map((letter) => letter.charCodeAt(0));
    const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
    const JPEG = [0xff, 0xd8, 0xff, 0xe0];
    const WEBP = [...codes("RIFF"), 0x24, 0x08, 0x00, 0x00, ...codes("WEBPVP8 ")];
    const file = (head, name, type, size = 1000) => {
      const data = new Uint8Array(Math.max(size, head.length));
      data.set(head);
      return new File([data], name, { type });
    };
    const upload = (fields) => uploadBrewPhoto({ error: null }, formData(fields));
    const saved = () => photos.map(({ name, type, size, caption }) => ({ name, type, size, caption }));
    const state = await upload({ photo: file(PNG, "../../my tea.png", "image/png", 4096), caption: "  Morning sencha " });
    expect(state).toEqual({ error: null });
    expect(saved()).toEqual([{ name: "photo-1.png", type: "image/png", size: 4096, caption: "Morning sencha" }]);
    expect(photos[0].bytes.length).toBe(4096);
    expect(Array.from(photos[0].bytes.slice(0, 8))).toEqual(PNG);
    expect(cache.revalidatedPaths).toEqual(["/gallery"]);
    
  2. takes JPEG and WebP photos too, named by their real format
    const codes = (text) => [...text].map((letter) => letter.charCodeAt(0));
    const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
    const JPEG = [0xff, 0xd8, 0xff, 0xe0];
    const WEBP = [...codes("RIFF"), 0x24, 0x08, 0x00, 0x00, ...codes("WEBPVP8 ")];
    const file = (head, name, type, size = 1000) => {
      const data = new Uint8Array(Math.max(size, head.length));
      data.set(head);
      return new File([data], name, { type });
    };
    const upload = (fields) => uploadBrewPhoto({ error: null }, formData(fields));
    const saved = () => photos.map(({ name, type, size, caption }) => ({ name, type, size, caption }));
    expect(await upload({ photo: file(JPEG, "IMG_2041.JPEG", "image/jpeg"), caption: "" })).toEqual({ error: null });
    expect(await upload({ photo: file(WEBP, "brew.webp", "image/webp", 2048), caption: "Cold brew" })).toEqual({ error: null });
    expect(saved()).toEqual([
      { name: "photo-1.jpg", type: "image/jpeg", size: 1000, caption: "" },
      { name: "photo-2.webp", type: "image/webp", size: 2048, caption: "Cold brew" },
    ]);
    
  3. asks for a photo when there's none, the input was left empty, or it's text
    const codes = (text) => [...text].map((letter) => letter.charCodeAt(0));
    const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
    const JPEG = [0xff, 0xd8, 0xff, 0xe0];
    const WEBP = [...codes("RIFF"), 0x24, 0x08, 0x00, 0x00, ...codes("WEBPVP8 ")];
    const file = (head, name, type, size = 1000) => {
      const data = new Uint8Array(Math.max(size, head.length));
      data.set(head);
      return new File([data], name, { type });
    };
    const upload = (fields) => uploadBrewPhoto({ error: null }, formData(fields));
    const saved = () => photos.map(({ name, type, size, caption }) => ({ name, type, size, caption }));
    for (const fields of [{ caption: "Hi" }, { photo: new File([], "", { type: "application/octet-stream" }) }, { photo: "tea.png" }]) {
      expect(await upload(fields)).toEqual({ error: "Choose a photo to upload." });
    }
    expect(photos).toEqual([]);
    expect(cache.revalidatedPaths).toEqual([]);
    
  4. turns down a photo over 2 MB before reading it
    const codes = (text) => [...text].map((letter) => letter.charCodeAt(0));
    const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
    const JPEG = [0xff, 0xd8, 0xff, 0xe0];
    const WEBP = [...codes("RIFF"), 0x24, 0x08, 0x00, 0x00, ...codes("WEBPVP8 ")];
    const file = (head, name, type, size = 1000) => {
      const data = new Uint8Array(Math.max(size, head.length));
      data.set(head);
      return new File([data], name, { type });
    };
    const upload = (fields) => uploadBrewPhoto({ error: null }, formData(fields));
    const saved = () => photos.map(({ name, type, size, caption }) => ({ name, type, size, caption }));
    const big = file(PNG, "big.png", "image/png", 2 * 1024 * 1024 + 1);
    for (const method of ["slice", "arrayBuffer", "bytes", "text", "stream"]) {
      big[method] = () => {
        throw new Error("The photo was read before its size was checked.");
      };
    }
    expect(await upload({ photo: big })).toEqual({ error: "Photos can be up to 2 MB." });
    expect(await upload({ photo: file(PNG, "fits.png", "image/png", 2 * 1024 * 1024) })).toEqual({ error: null });
    expect(saved().map((photo) => photo.size)).toEqual([2097152]);
    
  5. checks the first bytes, not just the type the browser sent
    const codes = (text) => [...text].map((letter) => letter.charCodeAt(0));
    const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
    const JPEG = [0xff, 0xd8, 0xff, 0xe0];
    const WEBP = [...codes("RIFF"), 0x24, 0x08, 0x00, 0x00, ...codes("WEBPVP8 ")];
    const file = (head, name, type, size = 1000) => {
      const data = new Uint8Array(Math.max(size, head.length));
      data.set(head);
      return new File([data], name, { type });
    };
    const upload = (fields) => uploadBrewPhoto({ error: null }, formData(fields));
    const saved = () => photos.map(({ name, type, size, caption }) => ({ name, type, size, caption }));
    const fakes = [
      file(codes("Steep for 3 minutes."), "notes.png", "image/png"),
      file(PNG, "tea.jpg", "image/jpeg"),
      file(codes("GIF89a"), "tea.gif", "image/gif"),
      file(JPEG, "tea.gif", "image/gif"),
      file(PNG.slice(0, 4), "half.png", "image/png"),
      file(PNG.slice(0, 3), "tiny.png", "image/png", 3),
      file([...codes("RIFF"), 0x24, 0x08, 0x00, 0x00, ...codes("AVI LIST")], "clip.webp", "image/webp"),
    ];
    for (const photo of fakes) {
      expect(await upload({ photo })).toEqual({ error: "Upload a JPEG, PNG, or WebP photo." });
    }
    expect(photos).toEqual([]);
    
  6. keeps the caption to 120 characters
    const codes = (text) => [...text].map((letter) => letter.charCodeAt(0));
    const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
    const JPEG = [0xff, 0xd8, 0xff, 0xe0];
    const WEBP = [...codes("RIFF"), 0x24, 0x08, 0x00, 0x00, ...codes("WEBPVP8 ")];
    const file = (head, name, type, size = 1000) => {
      const data = new Uint8Array(Math.max(size, head.length));
      data.set(head);
      return new File([data], name, { type });
    };
    const upload = (fields) => uploadBrewPhoto({ error: null }, formData(fields));
    const saved = () => photos.map(({ name, type, size, caption }) => ({ name, type, size, caption }));
    expect(await upload({ photo: file(PNG, "a.png", "image/png"), caption: "x".repeat(121) })).toEqual({ error: "Keep the caption to 120 characters." });
    expect(photos).toEqual([]);
    expect(await upload({ photo: file(PNG, "a.png", "image/png"), caption: ` ${"x".repeat(120)} ` })).toEqual({ error: null });
    expect(saved().map((photo) => photo.caption)).toEqual(["x".repeat(120)]);
    

Learn more

app/actions.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).