This site counts visits with analytics cookies only if you accept. Read the consent

Skip to content

AdvancedFile Upload

File Upload

Upload files with FormData and real-time progress tracking via XHR.

16 min readUpdated both modes

Overview

Courier supports file uploads using FormData in both direct and proxy modes. When you provide an onUploadProgress callback in a browser, Courier sends the request with XMLHttpRequest, whose upload events fetch lacks, for real network-level progress of the browser's own upload — unless the API sends its calls with a fetch of its own, which sends this one too (see Another fetch), or the call reads its answer as it comes (see Why XHR?), and no progress is reported. On a server — a direct call from Node, Deno or Bun — the body is streamed to fetch without being read into memory first: a FormData's files are read from disk as they are sent. Each chunk is reported once fetch has taken it, no event follows a cancel or a timeout, and a 307 or 308 redirect is followed with the body, as it is without progress, its files read again from where they are. A fetch built on undici before 8 — Node 22's and 24's own, or an API's own from an older undici — keeps a copy of a body it may have to send again for as long as it sends it, and Courier hands it none to keep: the copy of a FormData's or a Blob's body is a reading of its own, opened only if it is read. A ReadableStream body cannot be read again, so under Node 22 and 24, and through an API's own fetch under any Node (see One API), it follows no redirect: a redirect fails the call, as a network error does, unless you set redirect on the call yourself, and then the copy is kept. A retry policy does not send such a call again, nor one whose redirects run past 20 hops or to another scheme: the upstream would answer it with the same redirect. A ReadableStream body has no size to report against, so its totalBytes stays 0 until the last event, which reports 100% of what was sent.

Basic file upload

Create a FormData object with your files, pass it as variables, and use onUploadProgress to track progress:

components/avatar-upload.tsx
"use client"

import { useState } from "react"
import { caller } from "@/lib/caller"

export function AvatarUpload() {
  const [progress, setProgress] = useState(0)
  const [uploading, setUploading] = useState(false)

  async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return

    const formData = new FormData()
    formData.append("avatar", file)

    setUploading(true)
    setProgress(0)

    try {
      await caller.users
        .with({
          onUploadProgress: ({ percent }) => {
            setProgress(Math.round(percent * 100))
          },
        })
        .uploadAvatar(formData)
    } finally {
      setUploading(false)
    }
  }

  return (
    <div>
      <input type="file" accept="image/*" onChange={handleUpload} />
      {uploading && <progress value={progress} max={100} />}
    </div>
  )
}

Endpoint definition

Define upload endpoints using courier and defineGroup:

api/users.ts
import { courier, defineGroup } from "@noverax/courier/define"

const { endpoint } = courier()

type User = { id: number; name: string; avatarUrl: string }

const users = defineGroup({
  prefix: "users",
  endpoints: {
    uploadAvatar: endpoint.post("avatar").variables<FormData>().response<User>(),
    uploadDocument: endpoint.post("documents").variables<FormData>().response<{ url: string }>(),
  },
})

A file among the variables

A record of variables whose field holds a File, a Blob or bytes is sent as a multipart form, so an endpoint can name its fields and their types instead of taking a FormData:

api/books.ts
import { courier, defineGroup } from "@noverax/courier/define"

const { endpoint } = courier()

const books = defineGroup({
  prefix: "books",
  endpoints: {
    setCover: endpoint
      .post(":bookId/cover")
      .variables<{ bookId: string; title: string; cover: File }>()
      .response<{ url: string }>(),
  },
})

// caller.books.setCover({ bookId: "b7", title: "Dune", cover })
// → POST /books/b7/cover, a form: the field title=Dune and the file cover

The path's parameters are filled from the record and left out of the form, as they are from a FormData's fields. Each field is written as OpenAPI writes multipart/form-data by default, its value as JSON writes it in the record a proxy call carries, so a direct call and a proxy call send the same parts: a value's own toJSON is asked first, so a date is its ISO string; a string is a field; a finite number or a boolean is a field of its text; an object is a field of its JSON; a Blob or a File is a file, with the File's name and type; bytes are a file of their own; a list is a part for each item. A field JSON leaves out or writes as null — undefined, null, a function, NaN or Infinity, a date that is no date — is left out: a function's source is never sent. A record that holds no file goes as JSON. A source's bodySerializer writes the JSON body, so a record that holds a file goes as a form whatever it is. The form goes under the content type of its own encoding, which names its boundary: a Content-Type that the source, the call, a middleware or the endpoint's closure sets is left off it, as it is off a FormData.

What no form of the request carries is refused before anything is sent, with a ConfigurationError whose code is VARIABLE_NOT_ENCODABLE and whose message names where the value sits, not what it holds:

VariablesWhy they are refused
{ meta: { avatar: file } }a form sends an object as JSON, which keeps no file: give the file a field of its own
{ body: stream }a form's part is no stream: send the stream as the whole body
[file]a list has no field names: send an object
{ tags: new Set(…) }, { seen: new Map(…) }JSON writes either as {}, in a body or in an address
{ id: 12n }JSON writes no BigInt: send it as text, or give BigInt a toJSON of your own
meta.self = metaJSON writes no value inside itself; one met twice on different paths is written twice, and sent
a file in the variables of a get, head, options or delthose send their variables in the address, which holds text

A read sends a FormData's text fields in its address, as a browser sends a form whose method is GET; a file in it is refused the same way.

Through the proxy, the page cannot tell which verb an endpoint calls upstream, so a file in the variables of one that sends them in the address goes to the server, which refuses the call before anything reaches the upstream: the call rejects with an HTTPError of status 400 whose data is { "success": false, "code": "VARIABLE_NOT_ENCODABLE", "message": … }, the message a direct call's error has, and the server's log stays quiet, as it does for a call without its token.

Through the proxy, a record that holds a file travels as a record upload: a multipart body of its own media type, multipart/vnd.courier.variables, which holds the call's options, the record with each file's place, and the files. The server restores the record, so the endpoint's schema, its middleware and its closure see what a direct call sees, and the upstream receives the form a direct call sends — the same parts, each file passed through as it arrived.

Sent on as it arrives (uploadMode: "stream", below), the call's variables are a StreamedUpload, as a form's are: the upstream receives the form the record goes as, and the path takes no parameter from it.

A record upload is a format between the proxy client and the server: a server of an earlier release answers it 415, so deploy the client and the server together.

An API that takes only a form

A record that holds no file goes as JSON, which an API that reads only multipart/form-data refuses — an upload whose file may be left out, or one whose fields are all text. multipartBody, from @noverax/courier/define, writes the fields as a form whether a file is among them or not, each as a record's fields are written above:

ts
import { courier, multipartBody } from "@noverax/courier/define"

const { endpoint } = courier()

const uploadCover = endpoint
  .variables<{ title: string; cover?: Blob }>()
  .via((http, fields) => http.post("covers", undefined, { body: multipartBody(fields) }))

What no part carries is refused as it is from a direct call, with VARIABLE_NOT_ENCODABLE. The path is filled from the variables whatever the closure passes, so a closure takes a path's or a query's parameters out of the fields before it writes them: (http, { bookId, ...fields }) => …. A FormData, or the StreamedUpload the proxy passes with uploadMode: "stream", is a form already and is returned as it is: a closure that hands its variables on whole, as above, sends a form in every upload mode. The OpenAPI document Courier writes describes the endpoint's body as multipart/form-data.

Raw binary bodies

An upstream that takes the bytes themselves, rather than a multipart form, is called with the Blob, File or typed array as the variables. In direct mode it is sent as the body, with the Blob's own type as the content type:

ts
const putObject = endpoint.put("objects/raw").variables<Blob>()

await caller.storage.putObject(new Blob([bytes], { type: "image/png" }))

The proxy carries variables as JSON, a FormData or a record that holds a file, and refuses a raw body with ConfigurationError("PROXY_BODY_NOT_SUPPORTED"). From a browser, send the file in a FormData and let the endpoint's closure hand its bytes to the upstream:

ts
const putObject = endpoint
  .variables<FormData>()
  .via((http, form) => http.put("objects/raw", {}, { body: form.get("file") ?? undefined }))

Progress tracking

The onUploadProgress callback receives an UploadProgress object with three fields:

typescript
type UploadProgress = {
  // 0 to 1 — multiply by 100 for percentage
  percent: number

  // Bytes uploaded so far
  transferredBytes: number

  // Total file size in bytes
  totalBytes: number
}

// Usage:
onUploadProgress: (progress) => {
  console.log(`${Math.round(progress.percent * 100)}%`)
  console.log(`${progress.transferredBytes} / ${progress.totalBytes} bytes`)
}

lengthComputable

Progress events only fire when the browser knows the total size. For FormData uploads, this is always the case. The percent field ranges from 0 to 1.

A callback that throws fails the call with what it threw, as it was thrown, however the call is sent: the request stops, the call rejects with your error rather than a NetworkError, and a retry policy does not send it again. onDownloadProgress is called the same way.

A bar that moves smoothly

A browser reports an upload's progress every 100 ms or so — on a slow link a step of several percent each — and a server reports in bursts, as fetch takes the body. smoothProgress wraps the callback and moves the bar every 30 ms toward what the upload last reported, closing two thirds of the gap every 120 ms. It never runs ahead of the upload, never goes back, and comes to rest where the upload is, 100% included. Give each upload a wrapper of its own:

components/avatar-upload.tsx
"use client"

import { smoothProgress } from "@noverax/courier/client"
import { caller } from "@/lib/caller"

export async function uploadAvatar(form: FormData, setProgress: (percent: number) => void) {
  await caller.users
    .with({ onUploadProgress: smoothProgress(({ percent }) => setProgress(percent * 100)) })
    .uploadAvatar(form)
}

Send a file below to see both at once. Your browser uploads it to this site, which reads it at the pace you pick, as a slow link would. The amber bar moves as the browser reports progress; the blue one takes the same reports through smoothProgress.

File size
Upload speed

A recorded run · 8 MB at 4 MB/s — send your own

onUploadProgress

as the browser reports it

100.0%

reports
15
biggest jump
15%
longest wait
105 ms

smoothProgress(…)

the reports, smoothed

100.0%

moves
60
biggest jump
4%
longest wait
32 ms
  • browser reports
  • smoothProgress
  • the site answers

The file is zeros your browser makes. This site reads it at the pace you pick, as a slow link would, then drops it.

Progress counts the bytes handed to the network, as the browser or the runtime reports them. They reach the server a moment later — the platform buffers them on the way — so 100% comes a little before the answer does, and an upload to a slow server can rest at 100% while the server reads the last of it. Show the wait after 100% as such — "Processing…" — until the call resolves.

Progress in proxy mode

In proxy mode an upload travels twice: from the browser to the proxy route, then from the proxy to your backend. onUploadProgress measures the first hop only. The proxy reads the whole upload before it forwards anything, since it parses the form to hand the endpoint its fields, and then sends it on. So the progress reaches 100% when the proxy has the file, and the call resolves once the backend has received it and answered: behind a slow backend, a 25 MB upload can sit at 100% for several seconds. Sent on as it arrives, the upload goes no faster than the backend takes it, and the progress follows the backend's pace.

The proxy parses the upload as it arrives and keeps each file once, then sends the form on as a stream; how much of it stays in memory is where the proxy keeps an upload: under Node a 100 MB upload holds a few megabytes of the proxy's memory. It follows a redirect from your backend only where fetch can follow one without a copy, as above. Upload straight to storage — a pre-signed URL, or a direct call — when files are very large, or when the backend should see them while they arrive.

How the proxy keeps an upload meanwhile — in memory, on disk, or not at all, sent on as it arrives — and what it takes of one are on Uploads Through the Proxy.

Multi-file upload

Upload multiple files in a single request by appending them to the same FormData. You can also include metadata fields alongside the files:

components/document-upload.tsx
"use client"

import { useState } from "react"
import { caller } from "@/lib/caller"

export function DocumentUpload() {
  const [progress, setProgress] = useState(0)

  async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const files = e.target.files
    if (!files?.length) return

    const formData = new FormData()

    // Append multiple files under the same key or different keys
    for (const file of files) {
      formData.append("documents", file)
    }

    // Add metadata alongside files
    formData.append("folder", "invoices")
    formData.append("tags", "2024,finance")

    await caller.files
      .with({
        onUploadProgress: ({ percent }) => {
          setProgress(Math.round(percent * 100))
        },
      })
      .upload(formData)
  }

  return (
    <div>
      <input type="file" multiple onChange={handleUpload} />
      <p>{progress}% uploaded</p>
    </div>
  )
}

FormData compositionproxy mode

When FormData is sent through the proxy, Courier names the endpoint in the URL and writes the call's options as one field before yours. The server handler takes that field off before forwarding to your endpoint. In direct mode, FormData is sent as-is:

typescript
// When sending FormData through the proxy, Courier composes it like this:

// Your FormData:
formData.append("avatar", file)
formData.append("name", "profile-pic")

// What gets sent:
// POST /api/request?_s=api&_g=users&_m=uploadAvatar
// _options = '{"timeout":30000}' <- the call's options (JSON string)
// avatar   = File                <- your data
// name     = "profile-pic"       <- your data

// The server handler reads the first _options field as the options, and
// passes a FormData with only your data to the endpoint

The options field always comes first, and only the first part is read as the options, so a field of your own may share a name with it, or take any other name. A form that sends _method=PUT, as Laravel and Rails forms do, reaches your backend with that field intact.

Because the endpoint is in the URL, the proxy knows which call an upload is for as soon as it arrives. Studio shows the call while the upload is still on its way, and an upload over maxUploadBytes ends there with its 413 rather than never appearing.

Binary data outside FormDataproxy mode

A record of variables that holds a file in a field, or in a list there, reaches the server through the proxy as it was — see A file among the variables. Other variables travel to the proxy as JSON, which has no binary type: a Blob, File, ArrayBuffer, typed array or ReadableStream would arrive as {}. A proxy call whose variables hold one where no form carries it — a file deeper than a field, a stream in a field, binary data in a list — is therefore refused before it is sent, with a ConfigurationError whose code is VARIABLE_NOT_ENCODABLE and whose message names where it sits. A direct call from the server carries any body as it is.

typescript
// Refused in proxy mode: a form sends an object as JSON, which keeps no file
await caller.files.upload({ meta: { body: blob } })
// ConfigurationError: [courier] variables.meta.body is binary data, ...

// Reaches the server intact: the file sits in a field
await caller.files.upload({ name: "report.pdf", body: blob })

Empty file handling

An optional <input type="file"> left blank still submits a file: one with no name and no bytes. Courier leaves that placeholder out of the form it sends, so the backend does not receive an upload nobody chose. A file that has a name is sent even when it is empty — a .gitkeep or an empty log is a real file. Your own FormData is not edited; the placeholder is dropped from the copy that is sent.

typescript
const formData = new FormData(form)
// avatar    = File "photo.png", 120 KB  -> sent
// thumbnail = File "", 0 bytes          -> left out: the input was blank
// notes     = File "notes.txt", 0 bytes -> sent: a file somebody chose

Why XHR?

Courier uses XMLHttpRequest instead of fetch for uploads because the Fetch API does not support upload progress tracking. The switch is automatic and transparent:

typescript
// Why XHR instead of fetch?
//
// The Fetch API does not support upload progress tracking.
// ReadableStream + duplex: "half" only works on HTTP/2 and has
// limited browser support.
//
// XMLHttpRequest provides real network-level progress via the
// upload.onprogress event, which works on both HTTP/1.1 and HTTP/2.
//
// Courier automatically switches from fetch to XHR when
// onUploadProgress is provided. No configuration needed.

// Standard request — uses fetch
await caller.users.getAll()

// Upload request — automatically uses XHR
await caller.users
  .with({
    onUploadProgress: (p) => console.log(p.percent),
  })
  .uploadAvatar(formData)

HTTP/1.1 and HTTP/2

Unlike ReadableStream with duplex: "half", the XHR approach works on both HTTP/1.1 and HTTP/2 with full browser support.

A call that reads its answer as it comes, with stream: true, goes with fetch all the same: XMLHttpRequest hands an answer over only once all of it has arrived, and the stream is what the call asked for. In a browser and in a React Native app its upload then reports no progress; on a server it is counted as it is streamed, as any upload is there.

Limitations

When onUploadProgress is set, certain fetch-specific options are not available because the transport switches to XHR:

typescript
// When using onUploadProgress (XHR transport), these options are ignored:

await caller.files
  .with({
    onUploadProgress: ({ percent }) => setProgress(percent),
  
    // Ignored — XHR does not support the fetch cache API
    cache: "no-store",

    // Ignored — Next.js-specific fetch option, not available in XHR
    next: { revalidate: 0 },
  })
  .upload(formData)

// Also ignored in a browser: mode, redirect, keepalive, priority, integrity.
// In development, Courier logs a warning naming each ignored option.
// onDownloadProgress still works: XHR reports the answer as it arrives.

A ReadableStream body is read into memory before it is sent through XMLHttpRequest, which cannot send a stream — in a browser, and in a React Native app as expo/fetch reads one — and its progress then covers the bytes that were read. In a React Native app a stream is read whole without onUploadProgress too, as no fetch there sends one as it reads it. A call cancelled, or out of time, while its stream is read stops reading it and cancels it with the reason, and sends nothing. Without onUploadProgress it is streamed as it is, with duplex: "half" — which browsers allow only over HTTP/2 or later.

The code that reports an upload's progress loads with the first upload that asks for it, and where it does not load — a deployment took its chunk away, say — the upload is sent without progress and Courier warns once; only a React Native form holding a file on the device, which nothing else can send, fails instead, with MODULE_NOT_LOADED, and no retry sends it again.

Development warnings

In development mode, Courier logs a console warning for each ignored option so you can identify unintended usage early. In production, ignored options are silently skipped.

Uploads in Studio

With Studio attached, a call made with onUploadProgress shows its progress in the Timeline while it uploads, and its request detail says how much of the body has been sent. In proxy mode the browser names the call's Studio request id in an X-Courier-Rid header, and the proxy shows the call under that id, so the progress and the proxy's own events land on one row. The proxy announces the call as soon as it arrives, so an upload it refuses — a body over maxUploadBytes, say — appears as a failed request with its status.

Test uploads against a mock

A mock server takes uploads as your backend does, and can take them as a slow or strict one would, so the app's progress bar and its errors can be seen without the backend. Set its upload conditions in Studio's Network tab while it runs, or declare them with the mock:

ts
// courier.mocks.ts
import { courier, defineApi, defineGroup } from "@noverax/courier/define"
import { defineMocks, defineMockServer } from "@noverax/courier-mock"

const { endpoint } = courier()
type User = { id: number; name: string; avatarUrl: string }
const api = defineApi({
  baseURL: "https://api.example.com",
  groups: {
    users: defineGroup({
      prefix: "users",
      endpoints: {
        uploadAvatar: endpoint.post("avatar").variables<FormData>().response<User>(),
        uploadDocument: endpoint.post("documents").variables<FormData>().response<{ url: string }>(),
      },
    }),
  },
})

export default defineMocks({
  api: defineMockServer({
    source: api,
    network: {
      // Every upload arrives at 1.5 Mbps; none over 10 MB is taken
      uploads: { bandwidth: 1500, maxBytes: 10 * 1024 * 1024 },
      routeOverrides: [
        {
          routeId: "users:uploadAvatar",
          enabled: true,
          uploads: { maxBytes: 2 * 1024 * 1024, accept: ["image/png", "image/jpeg"] },
        },
      ],
    },
  }),
})
To seeSetThe app gets
Progress on a slow linkuploads.bandwidth, or Upload speedits progress moving at that speed, past the first part of the file the system takes at once
A file too largeuploads.maxBytes, or Size limit413, { "error": "The upload is 3.2 MB, over the 2 MB the mock takes" }, before the file is sent whole
A type the server does not takeuploads.accept, or File types415, { "error": "photo.heic (image/heic) is not a type the mock takes: image/png, image/jpeg" }
A connection lost partwaythe interrupt faulta network error once half the file has arrived
Any other errora status fault: "401", "403", "409", "422", "429", "500", "503", "507"…that status, { "error": "HTTP 507 Insufficient Storage (simulated)" }

A route's own override sets its limit and types, and the faults it fails with, in place of the mock's. See Network conditions for every setting, and how each one answers.

Next Steps