Registry / http-networking / form-auto-content

form-auto-content

JSON →
library3.2.1jsnpmunverified

form-auto-content is a utility library designed to simplify the creation of HTTP request payloads for web applications, intelligently determining the correct `Content-Type` header and payload format. It automatically switches between `application/x-www-form-urlencoded` and `multipart/form-data` based on the input data: if JavaScript `Stream` objects or `Buffer` instances are present within the input, it defaults to `multipart/form-data` for handling file uploads; otherwise, it constructs a standard `x-www-form-urlencoded` string. The current stable version is 3.2.1, indicating active development with a release cadence that includes minor and patch updates for new features, dependency management, and bug fixes, typically released as needed rather than on a fixed schedule. A key differentiator is its robust auto-sensing capability, allowing developers to pass a single JavaScript object without explicitly specifying the `enctype`. It gracefully handles complex data structures, including nested arrays, and supports advanced file options like custom filenames and content types for `multipart` fields. This makes it particularly useful for interacting with HTTP servers, especially within Node.js environments for server-side forms or API client libraries, and it integrates well with frameworks like Fastify and testing utilities such as `light-my-request`. The library also provides an API to customize the output field names for the generated payload stream and headers object.

npm install form-auto-content
INSTALL
IMPORT
SIG · FORM-AUTO-CONTENT
F
form-auto-content
http-networkingjavascriptv3.2.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

formAutoContent
import formAutoContent from 'form-auto-content';
import { formAutoContent } from 'form-auto-content';
The library exports a default function. Named imports are incorrect.
formAutoContent (CommonJS)
const formAutoContent = require('form-auto-content');
Standard CommonJS import for Node.js environments prior to ESM adoption.
formAutoContent (TypeScript with options)
const options = { payload: 'body', headers: 'head' } as const; const form = formAutoContent(data, options);
When providing custom output field names, use `as const` on the options object for accurate TypeScript type inference on the returned object.

Demonstrates how `form-auto-content` automatically handles `x-www-form-urlencoded` and `multipart/form-data` payloads, including file streams, buffers, arrays, and custom output field names.

import formAutoContent from 'form-auto-content'; import * as fs from 'fs'; import * as path from 'path'; import { Readable } from 'stream'; // Create dummy files for the example const tempFilePath1 = path.join(__dirname, 'the-file.txt'); const tempFilePath2 = path.join(__dirname, 'foo.md'); fs.writeFileSync(tempFilePath1, 'This is file content.'); fs.writeFileSync(tempFilePath2, '# Hello Markdown'); async function example() { // Scenario 1: x-www-form-urlencoded (no files/buffers) - auto-detected const formUrlEncoded = formAutoContent({ field1: 'value1', field2: ['value2', 'value2.2'], numberField: 123, }); console.log('--- URL-encoded Form ---'); console.log('Headers:', formUrlEncoded.headers); // Should be application/x-www-form-urlencoded const urlEncodedPayload = await streamToString(formUrlEncoded.payload as Readable); console.log('Payload:', urlEncodedPayload); console.log('\n'); // Scenario 2: multipart/form-data (with files/buffers) and custom output names - auto-detected const options = { payload: 'requestBody', headers: 'requestHeaders', // forceMultiPart: true // Can be uncommented to explicitly force multipart/form-data } as const; // 'as const' is crucial for TypeScript to infer correct return types const formMultiPart = formAutoContent({ name: 'John Doe', email: 'john@example.com', profilePic: fs.createReadStream(tempFilePath1), document: { value: fs.createReadStream(tempFilePath2), options: { filename: 'my-doc.md', contentType: 'text/markdown' } }, items: ['item1', 'item2'], jsonField: Buffer.from(JSON.stringify({ key: 'value', arr: [1, 2] })), }, options); console.log('--- Multipart Form with Custom Names ---'); console.log('Headers:', formMultiPart.requestHeaders); // Should be multipart/form-data // In a real scenario, you would pipe formMultiPart.requestBody to an HTTP client. console.log('Payload is a stream:', formMultiPart.requestBody instanceof Readable); console.log('\n'); // Clean up dummy files fs.unlinkSync(tempFilePath1); fs.unlinkSync(tempFilePath2); } // Helper function to convert a stream to string (for url-encoded example) function streamToString(stream: Readable): Promise<string> { const chunks: Buffer[] = []; return new Promise((resolve, reject) => { stream.on('data', chunk => chunks.push(chunk)); stream.on('error', reject); stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); }); } example().catch(console.error);
Debug
Known issues
breakingVersion 3.0.0 introduced a breaking change by updating Node.js engine requirements to `>=14.0.0`. Users on older Node.js versions must upgrade their environment or remain on v2.x.
fix
Upgrade your Node.js environment to version 14.0.0 or higher. For older environments, use `form-auto-content@2.x`.
affects: >=3.0.0
breakingMajor version 3.0.0 included 'deps and codebase maintenance', which may introduce subtle breaking changes beyond the stated Node.js engine bump. Always review your usage when upgrading from v2.x to v3.x.
fix
Thoroughly test your application when migrating from v2.x to v3.x. Refer to the GitHub changelog for specific dependency updates that might indirectly affect behavior.
affects: >=3.0.0
gotchaWhen using TypeScript with custom output options (e.g., `{ payload: 'body', headers: 'head' }`), you must use `as const` on the options object for correct type inference. Without it, TypeScript may not accurately narrow the return type, leading to errors when accessing the custom keys.
fix
Append `as const` to your options object, e.g., `{ payload: 'body', headers: 'head' } as const`.
affects: >=3.2.0
Errors
Common errors & fixes
TypeError: formAutoContent is not a function
Attempting to use `formAutoContent` with an incorrect import style, such as a named import (`import { formAutoContent } from 'form-auto-content';`) or a `require` call in an ESM module context.
fix
For ESM, use `import formAutoContent from 'form-auto-content';`. For CommonJS, use `const formAutoContent = require('form-auto-content');`.
Property 'payload' does not exist on type '{ body: Stream; head: {}; }.'
This TypeScript error occurs when custom output keys (like 'body' and 'head') are defined in the options, but the code attempts to access the default keys ('payload' and 'headers'), often without using `as const` on the options object for proper type inference.
fix
If custom keys were provided in the options, access them (e.g., `myForm.body`). Ensure the options object is declared with `as const` for accurate type inference: `const options = { payload: 'body', headers: 'head' } as const;`.
Upgrade
Version history
3.2.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources
form-auto-content — npm install form-auto-content · libregistry