An event's image field has been null since 01-04. Giving it a value looks like just another form, with an <input type="file">, and as far as the code goes it almost is. What changes is the nature of what comes in: a file can weigh a hundred times more than the rest of the request, it may not be what its name says, it has to be stored outside the database and, when it's replaced, someone has to delete the old one.

In this lesson organizers will upload their events' posters. You'll see how a File travels through a Server Action, the size limits, why you can't trust the extension or the declared type, how to isolate storage so you can use the disk in development and an object storage service in production, and what to do with files left without an owner.

  1. A file in FormData

An <input type="file" name="image"> adds a File object to the FormData. React sets the right encoding on the form, multipart/form-data; if you wrote encType, it would warn you it's unnecessary. In the action:

const file = formData.get('image') // string | File | null

if (file instanceof File) {
  file.name // 'poster.png': set by the browser
  file.type // 'image/png': declared by the browser
  file.size // Bytes
  const bytes = new Uint8Array(await file.arrayBuffer()) // The content
}
Property Trustworthy? What it's for
name No: it can be ../../app/page.tsx Showing it to whoever uploaded it
type No: it comes from the extension, or from whoever wrote the request Nothing on the server
size Yes: it's measured on what was received Limiting
The content It's the only real thing Deciding what it is

If nothing is chosen, a zero-size File arrives, not null. That's why you have to check the size as well as the type.

  1. Size

Next.js limits the body of action requests to 1 MB. It's a protection: reading huge bodies uses up memory and is an easy way to take down a server. It's adjusted in the configuration, and it's best to raise it only as much as needed:

// next.config.ts (addition)
experimental: {
  serverActions: { bodySizeLimit: '2.2mb' },
},
  • It's under experimental, even though Server Actions are stable; that's how the current version's documentation lists it.
  • It's global: it applies to every action. There's no per-action limit, which is a reason not to raise it much.
  • It counts the whole body, including the separators multipart adds. To allow 2 MB images you leave some margin.
  • If it's exceeded, the action doesn't run and the call fails: you can't return a friendly message. That's why it's also checked before submitting.
  • It isn't the only limit. A proxy in front (11-05) or the platform (11-04) will have their own, and when you add proxy.ts another one appears, proxyClientMaxBodySize, 10 MB by default. The smallest one wins.

There's another consequence. The action receives the whole file in memory. With 2 MB posters it doesn't matter; with videos, the approach is different (section 7).

// lib/images.ts (neutral)
export const MAX_IMAGE_SIZE = 2 * 1024 * 1024

export const IMAGE_EXTENSIONS = {
  'image/jpeg': 'jpg',
  'image/png': 'png',
  'image/webp': 'webp',
} as const

export type ImageType = keyof typeof IMAGE_EXTENSIONS

const IMAGE_KEY = /^events\/[0-9a-f-]{36}\.(jpg|png|webp)$/

export function isImageKey(key: string): boolean {
  return IMAGE_KEY.test(key)
}

export function imageUrl(key: string): string {
  return `/images/${key}`
}

  1. What it really is

Renaming virus.html to poster.png takes a second. If your domain served it as HTML, it would run code with your visitors' cookies. The extension and file.type can't rule it out, and neither can z.file().mime(…), which looks at the declared type.

Binary formats start with a few fixed bytes, their signature. These are checked against the content:

// lib/image-type.ts
import type { ImageType } from '@/lib/images'

function matches(bytes: Uint8Array, offset: number, expected: number[]): boolean {
  return expected.every((value, index) => bytes[offset + index] === value)
}

export function detectImageType(bytes: Uint8Array): ImageType | null {
  if (matches(bytes, 0, [0xff, 0xd8, 0xff])) return 'image/jpeg'
  if (matches(bytes, 0, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'image/png'

  // 'RIFF' + four size bytes + 'WEBP'
  const isRiff = matches(bytes, 0, [0x52, 0x49, 0x46, 0x46])
  if (isRiff && matches(bytes, 8, [0x57, 0x45, 0x42, 0x50])) return 'image/webp'

  return null
}
  • It's an allowlist, not a blocklist. Anything that isn't on it is rejected.
  • SVG isn't on it, on purpose. It's XML and can contain scripts.
  • We decide the extension based on what was detected; the original one is discarded.

The signature proves how the file starts, nothing more. A crafted file can be a valid PNG and contain something else at the same time, or describe an image with enormous dimensions that exhausts memory when it's opened. The strongest defense is re-encoding: opening the image with a library, scaling it down and storing the result.

// Example only, with the sharp library
const clean = await sharp(bytes)
  .rotate() // Applies the orientation given in the metadata
  .resize({ width: 1600, withoutEnlargement: true })
  .webp()
  .toBuffer()

It has another advantage: sharp doesn't keep the metadata unless you ask it to. Photos from a phone can carry the coordinates of the place where they were taken, which are personal data and shouldn't be published by accident. We don't include it in AgendaViva so as not to sidetrack the lesson; in an application open to the public, do it.

  1. Where it's stored

4.1. Why not in public/

Writing to public/ works in development, and that's why you see it so often. In production it fails in several ways:

  • The folder is part of the build. It's meant for files that already exist when the application is built. Each deployment starts from a clean copy and anything uploaded is lost.
  • Many platforms don't allow writing, or the disk disappears with the instance.
  • With several instances, the poster is on one and the others return 404.
  • There's no control. Everything in there is public, with max-age=0 and with whatever type its extension suggests.

Not in the database either: it would bloat the backups and every image would go through the pool. The usual approach is an object storage service (S3 or compatible) that stores bytes under a key, with only the key in the database.

4.2. An interface

So as not to depend on a cloud service during development, the application talks to an interface:

// lib/storage/types.ts
export interface FileStorage {
  save(key: string, content: Uint8Array): Promise<void>
  read(key: string): Promise<Uint8Array<ArrayBuffer> | null>
  remove(key: string): Promise<void>
}
// lib/storage/disk.ts
import 'server-only'
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { readEnv } from '@/lib/env'
import { isImageKey } from '@/lib/images'
import type { FileStorage } from './types'

function pathFor(key: string): string {
  if (!isImageKey(key)) throw new Error('Invalid file key')
  return path.join(readEnv().filesDir, key)
}

export const diskStorage: FileStorage = {
  async save(key, content) {
    const filePath = pathFor(key)
    await mkdir(path.dirname(filePath), { recursive: true })
    await writeFile(filePath, content, { flag: 'wx' }) // Fails if it already exists
  },

  async read(key) {
    try {
      return new Uint8Array(await readFile(pathFor(key)))
    } catch (error) {
      if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return null
      throw error
    }
  },

  async remove(key) {
    await rm(pathFor(key), { force: true }) // Doesn't fail if it's already gone
  },
}
// lib/storage/index.ts
import 'server-only'
import { diskStorage } from './disk'
import type { FileStorage } from './types'

// In production another implementation will be chosen here (module 11)
export function getStorage(): FileStorage {
  return diskStorage
}
// lib/env.ts: in the schema object…
FILES_DIR: z.string().trim().default('./data/files'),
// …and in the transformation
filesDir: variables.FILES_DIR,

Add /data/ to .gitignore and the variable to .env.example.

pathFor doesn't accept just any string. If the key contained ../, the path could escape the folder and overwrite the code; this is called path traversal. The regular expression makes it impossible, because it describes the complete shape. A path is never built with file.name: the key will be events/<uuid>.<extension>, which also never repeats, reveals nothing and has no trouble with accents or spaces.

  1. Uploading the poster

5.1. Changing the reference

// lib/data/dashboard.ts (addition)
export async function changeImage(
  organizerId: string,
  eventId: string,
  key: string | null,
): Promise<{ previous: string | null } | null> {
  const db = await getDb()
  return db.transaction(async (tx) => {
    const [event] = await tx
      .select({ image: events.image })
      .from(events)
      .where(isEditableBy(organizerId, eventId))
      .for('update')
    if (!event) return null

    await tx.update(events).set({ image: key }).where(eq(events.id, eventId))
    return { previous: event.image }
  })
}

It returns the key that was there so that file can be deleted. The lock prevents two simultaneous uploads from both thinking they're replacing the same one.

5.2. The action

The file and the database don't share a transaction: either one can fail after the other. The order is chosen so that the worst case is the least harmful:

flowchart LR
    A["Check<br/>permission and content"] --> B["Save<br/>new file"]
    B --> C["Change the key<br/>in the database"]
    C --> D["Delete<br/>previous file"]
    B -. "if it fails: nothing has changed" .-> X["Error"]
    C -. "if it fails: delete the new one" .-> X
    D -. "if it fails: an orphan is left" .-> Y["It's logged and cleaned up later"]
// actions/images.ts
'use server'

import { refresh } from 'next/cache'
import { getStorage } from '@/lib/storage'
import { changeImage, getEditableEvent } from '@/lib/data/dashboard'
import { identifier } from '@/lib/schemas/common'
import type { FormState } from '@/lib/forms'
import { IMAGE_EXTENSIONS, MAX_IMAGE_SIZE } from '@/lib/images'
import { detectImageType } from '@/lib/image-type'
import { getPlaceholderOrganizer } from '@/lib/placeholder-user'

export type ImageState = FormState<'image'>

function reject(reason: string): ImageState {
  return {
    status: 'error',
    message: "The poster wasn't saved.",
    errors: { image: [reason] },
    values: { image: '' },
  }
}

async function removeQuietly(key: string): Promise<void> {
  try {
    await getStorage().remove(key)
  } catch (error) {
    console.error(`Orphaned file ${key}:`, error)
  }
}

export async function uploadImage(
  eventId: string,
  _previous: ImageState,
  formData: FormData,
): Promise<ImageState> {
  const { id: organizerId } = await getPlaceholderOrganizer()

  if (
    !identifier.safeParse(eventId).success ||
    !(await getEditableEvent(organizerId, eventId))
  ) {
    return reject("This event can't be edited.")
  }

  const file = formData.get('image')
  if (!(file instanceof File) || file.size === 0) return reject('Choose an image.')
  if (file.size > MAX_IMAGE_SIZE) return reject('The image is larger than 2 MB.')

  const bytes = new Uint8Array(await file.arrayBuffer())
  const type = detectImageType(bytes)
  if (!type) return reject('It must be a JPEG, PNG or WebP image.')

  const key = `events/${crypto.randomUUID()}.${IMAGE_EXTENSIONS[type]}`
  let change: { previous: string | null } | null = null

  try {
    await getStorage().save(key, bytes)
    change = await changeImage(organizerId, eventId, key)
  } catch (error) {
    console.error('Error saving a poster:', error)
  }

  if (!change) {
    await removeQuietly(key)
    return reject('There was a problem saving it. Please try again.')
  }
  if (change.previous) await removeQuietly(change.previous)

  refresh()
  return { status: 'success', message: 'Poster saved.' }
}
  • Permission is checked twice, and both checks make sense. The first avoids the work; the second, inside the changeImage transaction, is the one that guarantees it.
  • Each upload uses a new key, also when replacing. That way the URL changes and caches don't serve the old image, and nothing that another page is showing is ever overwritten.
  • An orphan is acceptable; a broken reference isn't. If the previous file were deleted first and the rest failed, the event would point to something that doesn't exist.
  • crypto.randomUUID() poses no problem here: an action isn't prerendered.
  • With a published event you'd also have to call invalidateEvent. For now only drafts and events in review are edited; it'll be added in 11-03.

5.3. The form, with a preview

It goes separately from the event form. A file field is cleared after every submission and doesn't accept a default value: together, every error in the title would force you to choose the image again. Besides, it allows a different path for each thing.

// app/(dashboard)/dashboard/events/_components/image-form.tsx
'use client'

import { type ChangeEvent, useActionState, useState } from 'react'
import { uploadImage } from '@/actions/images'
import { SubmitButton } from '@/components/submit-button'
import { Field } from '@/components/field'
import { FormMessage } from '@/components/form-message'
import { INITIAL_STATE } from '@/lib/forms'
import { IMAGE_EXTENSIONS, MAX_IMAGE_SIZE, imageUrl } from '@/lib/images'

interface Props {
  eventId: string
  image: string | null
}

export function ImageForm({ eventId, image }: Props) {
  const [state, formAction] = useActionState(uploadImage.bind(null, eventId), INITIAL_STATE)
  const errors = state.status === 'error' ? state.errors.image : undefined

  return (
    <form action={formAction} className="mt-8 max-w-xl">
      <h2 className="mb-2 text-xl font-semibold">Poster</h2>
      <FormMessage state={state} />
      <ImagePicker key={image} image={image} errors={errors} />
      <SubmitButton pendingText="Uploading…" className="border px-3">Save poster</SubmitButton>
    </form>
  )
}

function ImagePicker({ image, errors }: Pick<Props, 'image'> & { errors?: string[] }) {
  const [preview, setPreview] = useState<string | null>(null)
  const src = preview ?? (image && imageUrl(image))

  function handleChange({ currentTarget: input }: ChangeEvent<HTMLInputElement>) {
    const file = input.files?.[0]
    const tooLarge = file !== undefined && file.size > MAX_IMAGE_SIZE
    input.setCustomValidity(tooLarge ? 'The image is larger than 2 MB.' : '')

    if (preview) URL.revokeObjectURL(preview)
    setPreview(file && !tooLarge ? URL.createObjectURL(file) : null)
  }

  return (
    <>
      {src && <img src={src} alt="Poster" className="mb-2 aspect-video object-cover" />}
      <Field label="Image" hint="JPEG, PNG or WebP, up to 2 MB" errors={errors}>
        {(attributes) => (
          <input
            {...attributes}
            type="file"
            name="image"
            accept={Object.keys(IMAGE_EXTENSIONS).join(',')}
            onChange={handleChange}
            required
          />
        )}
      </Field>
    </>
  )
}
  • URL.createObjectURL gives the chosen file a local address. Nothing is uploaded. It takes up memory until it's released with revokeObjectURL, which we call when another file is chosen. We don't do it in an effect's cleanup: with Cache Components, hiding the page would run it, and when you came back the preview would be broken.
  • setCustomValidity makes the browser block the submission with our message. That's what avoids running into bodySizeLimit, where we couldn't explain anything.
  • accept filters the file picker. It's a convenience; it can be bypassed.
  • key={image}: when a new image is saved, the picker is created again and the preview gives way to the final image.
  • It works without JavaScript, with no preview and with the server's check.
  • There's no progress bar. A Server Action doesn't report the bytes sent. For 2 MB, "Uploading…" is enough.

In EditEventPage, place it below the form: <ImageForm eventId={event.id} image={event.image} />. ESLint's @next/next/no-img-element rule will warn about the <img>; that's correct, and on the event page it'll be resolved in 09-02.

  1. Serving the images

// app/images/[...key]/route.ts
import { getStorage } from '@/lib/storage'
import { isImageKey, IMAGE_EXTENSIONS } from '@/lib/images'

export async function GET(
  _request: Request,
  { params }: RouteContext<'/images/[...key]'>,
) {
  const key = (await params).key.join('/')
  const content = isImageKey(key) ? await getStorage().read(key) : null
  if (!content) return new Response(null, { status: 404 })

  const type = Object.entries(IMAGE_EXTENSIONS).find(([, extension]) =>
    key.endsWith(`.${extension}`),
  )?.[0]

  return new Response(content, {
    headers: {
      'Content-Type': type ?? 'application/octet-stream',
      'X-Content-Type-Options': 'nosniff',
      'Cache-Control': 'public, max-age=31536000, immutable',
    },
  })
}
// EventDetails, after the heading (imports imageUrl)
{event.image && (
  <img src={imageUrl(event.image)} alt="" className="my-4 aspect-video w-full object-cover" />
)}
  • The key is validated before touching the disk, just as when writing.
  • The type comes from our extension, which in turn came from the content. nosniff prevents the browser from deciding on its own that the thing looks like HTML.
  • immutable for a year is safe because a key never changes its content.
  • It isn't private. A draft's poster can be seen if its address is known; with a random identifier it can't be guessed, but it isn't protected either. A confidential document would require checking the session on every request.
  • aspect-video reserves the space and avoids the jump when loading.

In production this Route Handler isn't needed: the images are served by the storage service, usually behind a CDN, and imageUrl switches to returning that address. That's why everyone builds the URLs with that function.

  1. In production: direct upload

With object storage there are two possible designs. The first is the same as now, swapping the FileStorage implementation: the file goes through your server. The second avoids that: the server signs a temporary permission and the browser uploads directly to the storage service.

sequenceDiagram
    participant B as Browser
    participant A as AgendaViva
    participant O as Object storage
    B->>A: requestUpload (event, type, size)
    A->>A: permission, limits and new key
    A-->>B: signed URL, valid for one minute
    B->>O: PUT with the file
    O-->>B: 200
    B->>A: confirmUpload (event, key)
    A->>O: read the size and the first bytes
    A->>A: save the key in the database
// Sketch: not part of the project
// npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'

const client = new S3Client({ region, endpoint, credentials })

const url = await getSignedUrl(
  client,
  new PutObjectCommand({ Bucket: bucket, Key: key, ContentType: type }),
  { expiresIn: 60 },
)
Through your server Direct upload
Complexity One action Two actions and a request from the browser
Memory and bandwidth Yours The storage service's
Size limit bodySizeLimit and the platform's The storage service's
Progress No Yes, with XMLHttpRequest
Validating the content Before saving Afterwards: it's already in storage
Without JavaScript Yes No

The fifth row is the one most often forgotten. With a signed URL, you haven't seen what arrives: you have to check it in confirmUpload and delete whatever isn't valid. It's also a good idea for the key to go to a temporary area that empties itself, for the URL to be short-lived, and for confirming to require the same permission as requesting. If you need the storage service itself to reject by size, there's another variant, the signed POST form with conditions. You'll also have to configure CORS on the storage service and allow it in the content security policy (08-05).

For 2 MB posters, the first design is enough.

  1. Orphans

A file with no reference appears if a delete fails, if the server stops between two steps or if an event is removed. There's no way to avoid them completely; they're collected periodically:

// scripts/clean-files.ts
import '../lib/db/load-env'
import { readdir, rm, stat } from 'node:fs/promises'
import path from 'node:path'
import { drizzle } from 'drizzle-orm/node-postgres'
import { isNotNull } from 'drizzle-orm'
import { Pool } from 'pg'
import { events } from '../lib/db/schema'

const ONE_DAY = 24 * 60 * 60 * 1000

async function clean(): Promise<void> {
  const dir = path.join(process.env.FILES_DIR || './data/files', 'events')
  const files = await readdir(dir)
  const pool = new Pool({ connectionString: process.env.DATABASE_URL })

  try {
    const rows = await drizzle({ client: pool })
      .select({ image: events.image })
      .from(events)
      .where(isNotNull(events.image))
    const used = new Set(rows.map(({ image }) => image))

    for (const name of files) {
      const filePath = path.join(dir, name)
      const { mtimeMs } = await stat(filePath)
      if (used.has(`events/${name}`) || Date.now() - mtimeMs < ONE_DAY) continue

      await rm(filePath)
      console.log(`Deleted: ${name}`)
    }
  } finally {
    await pool.end()
  }
}

clean().catch((error: unknown) => {
  console.error(error)
  process.exitCode = 1
})
{ "files:clean": "tsx scripts/clean-files.ts" }

The one-day margin isn't needless caution: a file that's just been saved may be about to be referenced. And the directory is read before the database: that way, a file that arrives in the meantime isn't on the list. If the query fails, it throws before deleting anything.

With object storage, cleaning up the temporary area is usually delegated to its expiration rules.

Common Mistakes and Tips

  • Saving to public/. It works until the first deployment.
  • Using file.name as a path or as a name.
  • Deciding by the extension or by type.
  • Accepting SVG as if it were any other image.
  • Raising bodySizeLimit "just in case". It affects every action.
  • Not checking the size before submitting: once the limit is exceeded, no message can be given.
  • Deleting the previous file before saving the new one.
  • Reusing the same key when replacing. Caches serve the old one.
  • Forgetting nosniff and a Content-Type of your own when serving.
  • Taking what's uploaded with a signed URL as validated.
  • Publishing photos with their metadata.

Exercises

Exercise 1: removing the poster

Add a "Remove poster" button with its own action, which sets image to null and deletes the file. It must be idempotent and not leave a broken reference if something fails.

Solution

// actions/images.ts
export async function removeImage(eventId: string): Promise<void> {
  const { id } = await getPlaceholderOrganizer()
  if (!identifier.safeParse(eventId).success) return

  const change = await changeImage(id, eventId, null)
  if (change?.previous) await removeQuietly(change.previous)
  refresh()
}
// Another form, next to the image one
{image && (
  <form action={removeImage.bind(null, eventId)}>
    <SubmitButton pendingText="Removing…">Remove poster</SubmitButton>
  </form>
)}

First the reference is removed and then the file: if the delete fails, an orphan is left rather than a broken poster. The second time, previous is null and there's nothing to delete. The course keeps this addition.

Exercise 2: reviewing an upload

Find the problems in this action.

'use server'

export async function upload(formData: FormData) {
  const file = formData.get('photo') as File
  if (!file.type.startsWith('image/')) throw new Error('Not an image')

  const filePath = `./public/photos/${file.name}`
  await writeFile(filePath, Buffer.from(await file.arrayBuffer()))
  await savePath(formData.get('userId') as string, `/photos/${file.name}`)
}

Solution

  1. as File checks nothing: if a string arrives, it fails with a confusing error; if the field is empty, size is 0 and it's accepted.
  2. type is declared by the sender, and image/ includes SVG.
  3. The original name allows path traversal and overwriting other people's photos with the same name.
  4. public/ isn't suitable for content created at runtime.
  5. The user comes from the form: anyone can change anyone's photo.
  6. There's no size limit of its own.
  7. The previous photo is left orphaned, and if savePath fails, so is the new one.
  8. It throws an error for an expected rejection, and it doesn't renew the screen.

Exercise 3: an in-memory storage

For the tests in 10-03 it's useful to have a FileStorage that doesn't touch the disk. Write it and say what else would have to change for the actions to use it.

Solution

// lib/storage/memory.ts
import type { FileStorage } from './types'

export function createMemoryStorage(): FileStorage {
  const files = new Map<string, Uint8Array<ArrayBuffer>>()

  return {
    async save(key, content) {
      if (files.has(key)) throw new Error('The key already exists')
      files.set(key, new Uint8Array(content))
    },
    async read(key) {
      return files.get(key) ?? null
    },
    async remove(key) {
      files.delete(key)
    },
  }
}

It fulfills the same contract, including failing if the key exists. The actions call getStorage(), so it's enough for that function to return this one in tests, by replacing the module. That's the advantage of having put an interface in between; the example isn't kept.

Conclusion

A file reaches a Server Action as a File inside FormData, limited by bodySizeLimit and loaded into memory. Its name and its type can't be trusted: you decide by the content and store it under a key of your own. Storage sits behind an interface, with the disk in development and an object storage service in production, perhaps with direct upload and signed URLs. Since the file and the database don't share a transaction, the order of the steps makes the worst case an orphan, and a periodic cleanup collects them.

That's the end of module 6. AgendaViva now writes: it saves preferences, books and cancels without losing spots, creates and edits events with their posters, validates on the server and reports what's happening. The doors we've opened are walked through by people, from our pages. What's left are the ones other programs use, which have already peeked through with the spots, the suggestions and the images. Module 7, devoted to the backend, starts with Route Handlers: HTTP Endpoints.

© Copyright 2026. All rights reserved