Skip to content
jshacks.dev
Browser

FormData in the Browser: Build, Read and Send Forms

Use FormData in the browser to read form fields, add files, build multipart bodies and send them with fetch, with the gotchas around checkboxes and headers.

7 min read
Summarize in AI
Flat illustration of an envelope and a notification bell, with the Google Chrome, Resend, slack, Mailgun and Vite logos.

Every web form ends the same way: a set of names and values leaves the page and reaches a server. The FormData interface is the browser's own container for those pairs. It reads a whole <form> in one call, holds text and files side by side, and is the body type that fetch knows how to send as multipart/form-data without any extra code. This post explains how to create a FormData object, how to read, change and loop over it, how it treats checkboxes, files and disabled fields, how to send it with fetch, and how to turn it into plain objects or query strings when you need JSON instead. The reference is the MDN page for FormData and the XMLHttpRequest Standard, where the interface is defined.

Creating a FormData object

There are two ways to get one. Call the constructor with nothing for an empty container, or pass it a form element to capture the current values of that form.

page.htmlHTML
<form id="signup">
  <input name="email" value="[email protected]">
  <input name="plan" type="radio" value="free" checked>
  <input name="plan" type="radio" value="pro">
  <input name="newsletter" type="checkbox" value="yes">
  <select name="country">
    <option value="vn" selected>Vietnam</option>
    <option value="us">United States</option>
  </select>
  <button name="action" value="join">Join</button>
</form>
create.jsJavaScript
const form = document.getElementById("signup");
const data = new FormData(form);

for (const [name, value] of data) {
  console.log(name, "=", value);
}
Text
email = [email protected]
plan = free
country = vn

The loop shows what the browser would submit. The unchecked checkbox newsletter is missing, because browsers leave unchecked checkboxes out of a submission, and so is the radio that is not selected. The submit button is also missing: when you pass only the form, no submitter is recorded. A button's name and value appear only if you tell the constructor which control triggered the submission, which is the second argument, and is supported in current browsers.

submitter.jsJavaScript
form.addEventListener("submit", (event) => {
  const data = new FormData(form, event.submitter);
  console.log(data.get("action"));
});
Text
join

The submitter property of the submit event is the button that was clicked. Passing it makes the object match a native submission exactly, which matters when a form has several buttons with different meanings.

Reading values

The object has a small, consistent set of methods. A field name can appear more than once, so get returns the first value and getAll returns an array of every value.

MethodReturns
get(name)The first value for the name, or null
getAll(name)An array of all values for the name
has(name)true if the name is present
entries(), keys(), values()Iterators over the pairs
read.jsJavaScript
const data = new FormData();
data.append("tag", "js");
data.append("tag", "dom");

console.log(data.get("tag"));
console.log(data.getAll("tag"));
console.log(data.has("missing"));
Text
js
[ 'js', 'dom' ]
false

A missing name makes get return null, not an empty string, so test with has or compare with null when the difference matters.

Changing values

Three methods write to the container. append always adds a new pair, which is how you build a multi-value field. set replaces every existing value for the name with one value, or adds it if absent. delete removes every pair with the name.

write.jsJavaScript
const data = new FormData();
data.append("tag", "js");
data.append("tag", "dom");
data.set("tag", "browser");
data.append("page", "1");
data.delete("page");

console.log([...data]);
Text
[ [ 'tag', 'browser' ] ]

A common bug is calling append in a loop where set was meant, which sends the same field twice. If the server reads the first value, the update seems to be ignored. Use set when a name must be unique.

Files and Blobs

A FormData value is a string or a File. Appending a Blob stores it as a File with a name, which you can choose with the third argument.

files.jsJavaScript
const data = new FormData();
const input = document.getElementById("avatar");

data.append("avatar", input.files[0]);

const note = new Blob(["hello"], { type: "text/plain" });
data.append("note", note, "note.txt");

const file = data.get("note");
console.log(file instanceof File, file.name, file.size, file.type);
Text
true note.txt 5 text/plain

Without the third argument, an appended Blob gets the file name blob, which servers then store under a meaningless name. Always pass a file name when you build a file from generated data. Plain strings and numbers are stored as strings: appending 5 stores "5", and the server decides how to parse it.

Sending with fetch

Give fetch a FormData as the body and it sends multipart/form-data, with a boundary string generated by the browser. The part that people get wrong is the Content-Type header: do not set it.

send.jsJavaScript
const data = new FormData(document.getElementById("signup"));
data.append("source", "landing-page");

const response = await fetch("/api/signup", {
  method: "POST",
  body: data,
});

console.log(response.status);
Text
200

The browser writes Content-Type: multipart/form-data; boundary=... itself, and the boundary must match the one used in the body. If you set the header by hand to multipart/form-data, the boundary is missing, and the server cannot split the parts. Remove the header and the request works. Cross-origin requests with this body type count as simple requests as far as the content type goes, so the usual CORS rules still apply to the rest of the call.

Turning it into JSON or a query string

Sometimes the API wants JSON. Object.fromEntries converts the pairs into an object, with one catch: repeated names collapse into the last value.

json.jsJavaScript
const data = new FormData();
data.append("name", "Ada");
data.append("tag", "js");
data.append("tag", "dom");

console.log(Object.fromEntries(data));
Text
{ name: 'Ada', tag: 'dom' }

To keep every value of a repeated name, group them yourself:

group.jsJavaScript
const body = {};

for (const key of new Set(data.keys())) {
  const values = data.getAll(key);
  body[key] = values.length > 1 ? values : values[0];
}

console.log(JSON.stringify(body));
Text
{"name":"Ada","tag":["js","dom"]}

For a query string, pass the object to URLSearchParams. This works only when there are no files, because a File cannot be written to a URL, and TypeScript rejects the call for that reason.

query.jsJavaScript
const params = new URLSearchParams(new FormData(form));
console.log(params.toString());
Text
email=ada%40example.com&plan=free&country=vn

The result is the same as the browser's own application/x-www-form-urlencoded encoding, with @ written as %40. A URLSearchParams body also gets the right content type from fetch.

Which fields are included

FormData follows the rules for a native submission, and knowing them avoids surprises.

  • Disabled controls are skipped. A disabled input never reaches the server, even if it has a value.

  • A control without a name attribute is skipped.

  • Unchecked checkboxes and radio buttons are skipped. A checked checkbox without a value sends on.

  • File inputs with no file chosen send an empty file part with an empty name.

  • Fields outside the form that point to it with the form attribute are included.

When the server needs to know that a checkbox was unchecked, add a hidden field with the same name before it, so a default value is always sent, or read the checkbox state in script and write it in with set.

The formdata event

When a submission starts, or when you create new FormData(form), the browser fires a formdata event on the form. A listener can add or change entries at the last moment, which is a tidy way for a custom control to contribute its value.

formdata-event.jsJavaScript
form.addEventListener("formdata", (event) => {
  event.formData.set("timezone", Intl.DateTimeFormat().resolvedOptions().timeZone);
});

const data = new FormData(form);
console.log(data.get("timezone"));
Text
Asia/Ho_Chi_Minh

The value depends on the visitor's machine, so yours will differ. The event is the supported way for form-associated custom elements to participate, although most code needs only set before sending.

Upload progress and large files

fetch has no upload progress event, and a FormData body is not a stream you can watch. If you need a progress bar for large uploads, use XMLHttpRequest, whose upload object fires progress events, and send the same FormData through it. For very large files, consider sending the file as the raw body with a PUT, or splitting it with Blob.slice and uploading in chunks, since a single multipart request cannot resume after a connection drop.

progress.jsJavaScript
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/upload");

xhr.upload.addEventListener("progress", (event) => {
  if (event.lengthComputable) {
    console.log(`${Math.round((event.loaded / event.total) * 100)}%`);
  }
});

xhr.send(new FormData(document.getElementById("upload")));
Text
12%
47%
100%

The percentages are examples; the number of events and their values depend on the file and the network.

Security and validation notes

Treat everything in a FormData as untrusted once it reaches the server, since anyone can send a request without your page. Check file type and size on the server, not just in the accept attribute, and never trust the file name the client sends. On the page, avoid putting secrets such as access tokens in form fields that will be sent to a third-party origin, and if the request changes state, protect it with a CSRF token or a SameSite cookie, which the browser applies to multipart requests the same as any other.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.