Object to FormData Serializer
object-to-formdata is a utility library for JavaScript that efficiently serializes plain JavaScript objects into `FormData` instances, a crucial browser API for sending data via `multipart/form-data` requests. Currently at version 4.5.1, it provides options to control how arrays, nulls, booleans, and object/array notation in keys are handled during serialization. The package is actively maintained with regular updates and bug fixes, indicated by its recent releases. Its primary differentiator is the configurable serialization logic, allowing developers to fine-tune how complex data structures are represented in `FormData` compared to manual construction or simpler serializers.
Common errors
-
TypeError: (0 , object_to_formdata__WEBPACK_IMPORTED_MODULE_0__.formData) is not a function
cause Attempting to use the old `formData` named export after upgrading to version 4.0.0 or higher.fixThe named export was renamed. Change `import { formData } from 'object-to-formdata';` to `import { serialize } from 'object-to-formdata';`. -
TypeError: object_to_formdata__WEBPACK_IMPORTED_MODULE_0__.default is not a function
cause Attempting to import `object-to-formdata` as a default export, which was removed in version 3.0.0.fixThe package no longer has a default export. Change `import serialize from 'object-to-formdata';` to `import { serialize } from 'object-to-formdata';`. -
FormData entries show '[object Object]' for nested objects or arrays instead of serialized keys.
cause This is not an error but expected browser behavior. `FormData` itself flattens to key-value pairs where values are strings or `File`/`Blob` objects. Nested structures are flattened into keys like `parent[child]` or `array[0]`, not actual nested objects.fixThe library correctly serializes nested objects and arrays into appropriate `FormData` keys. When inspecting `FormData` via `console.log`, you'll see the flattened key-value pairs, which is how HTTP `multipart/form-data` works. Ensure your backend is configured to parse these nested key structures (e.g., using a library like `multer` in Node.js).
Warnings
- breaking Starting with version 3.0.0, the package removed its default export. Attempts to import it using `import serialize from 'object-to-formdata'` will fail.
- breaking Version 4.0.0 introduced a breaking change by renaming the primary named export from `formData` to `serialize`.
- gotcha By default, boolean values (`true`/`false`) are serialized as the strings 'true'/'false'. If your backend expects integers (1/0), you need to configure this behavior.
- gotcha Arrays are serialized with bracket notation by default (e.g., `items[]`). If you need indexed keys (e.g., `items[0]`), or no array notation for files/attributes, specific options are required.
Install
-
npm install object-to-formdata -
yarn add object-to-formdata -
pnpm add object-to-formdata
Imports
- serialize
import serialize from 'object-to-formdata'; // incorrect since v3
import { serialize } from 'object-to-formdata'; - serialize (CommonJS)
const serialize = require('object-to-formdata'); // incorrect since v3const { serialize } = require('object-to-formdata'); - FormData (Type)
import type { FormData } from 'object-to-formdata';
Quickstart
import { serialize } from 'object-to-formdata';
const userProfile = {
name: 'John Doe',
email: 'john.doe@example.com',
age: 30,
isActive: true,
roles: ['admin', 'editor'],
address: {
street: '123 Main St',
city: 'Anytown',
zip: '12345'
},
avatar: new File([''], 'avatar.png', { type: 'image/png' })
};
const options = {
indices: true, // Serialize roles[0]=admin, roles[1]=editor
booleansAsIntegers: true, // Serialize isActive=1
nullsAsUndefineds: true, // Ignore null values
dotsForObjectNotation: false // Use brackets for objects (address[street])
};
const formData = serialize(userProfile, options);
// To see the contents (FormData is not directly iterable by value without special methods):
for (const pair of formData.entries()) {
console.log(`${pair[0]}: ${pair[1]}`);
}
// Example of appending to an existing FormData instance
const existingData = new FormData();
existingData.append('tenantId', '123-abc');
const combinedFormData = serialize({ metadata: 'important' }, {}, existingData);
for (const pair of combinedFormData.entries()) {
console.log(`Combined: ${pair[0]}: ${pair[1]}`);
}