Skip to content

fix(formToJSON): support 'length' as a field name - #11353

Closed
princejain756 wants to merge 1 commit into
axios:v1.xfrom
princejain756:fix-formdata-length-key
Closed

princejain756 wants to merge 1 commit into
axios:v1.xfrom
princejain756:fix-formdata-length-key

Conversation

@princejain756

@princejain756 princejain756 commented Oct 21, 2026 •

Copy link
Copy Markdown

axios.formToJSON() threw RangeError: Invalid array length for an ordinary field named length (metadata[length], metadata.length, metadata[length][unit]).

The parser descends through intermediate arrays, and an array's own length property collides with the field key: hasOwnProp sees it and the merge path assigns a non-numeric value to array.length.

When the next path segment is length, the intermediate array is now converted to a plain object before descending, so the named key stores normally. Numeric siblings written earlier (e.g. metadata[0] before metadata[length]) are preserved by the conversion.

Fixes #11295


Summary by cubic

Description

axios.formToJSON() previously threw RangeError: Invalid array length for ordinary fields named length (e.g. metadata[length], dims.length). The parser descends through intermediate arrays, whose own length property collides with the field key: hasOwnProp sees it and the merge path assigns a non-numeric value to array.length.

  • Summary of changes: when the next path segment is length, the intermediate array is now converted to a plain object before descending, so the named key stores normally.
  • Reasoning: an array's length is an own property that cannot hold named field values, so converting to an object avoids the collision; numeric siblings written earlier (e.g. metadata[0]) are preserved by the conversion.
  • Additional context: fixes formToJSON throws for nested fields named length #11295.

Docs

No documentation update needed; this is a bug fix with no API surface change.

Testing

Added a test in tests/unit/helpers/formDataToJSON.test.js covering length as a field name across metadata[length], metadata[0], size[length][unit], and dims.length.

Semantic version impact

Patch version change. This is a non-breaking bug fix; no public API or behavior beyond the crash is changed.

Written for commit f8f35f0. Summary will update on new commits.

View guided diff

A field named 'length' (e.g. metadata[length]) crashed with
RangeError: Invalid array length. The parser descends through
intermediate arrays, whose own 'length' property collides with the
field key.

When the next path segment is 'length', the intermediate array is now
converted to an object before descending, so the named key can be
stored. Numeric siblings written before the 'length' field are kept.

Fixes axios#11295

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files

Confidence score: 4/5

  • formDataToJSON.test.js appends metadata[length] first, so the test won't catch conversion dropping a previously written numeric sibling. Append metadata[0] first.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="tests/unit/helpers/formDataToJSON.test.js">

<violation number="1" location="tests/unit/helpers/formDataToJSON.test.js:222">
P2: This test does not cover preserving a previously written numeric sibling because `metadata[length]` is appended first. Append `metadata[0]` before `metadata[length]` so the assertion fails if conversion drops existing array entries.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

Comment on lines +222 to +223
formData.append('metadata[length]', 'long');
formData.append('metadata[0]', 'a');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This test does not cover preserving a previously written numeric sibling because metadata[length] is appended first. Append metadata[0] before metadata[length] so the assertion fails if conversion drops existing array entries.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/unit/helpers/formDataToJSON.test.js, line 222:

<comment>This test does not cover preserving a previously written numeric sibling because `metadata[length]` is appended first. Append `metadata[0]` before `metadata[length]` so the assertion fails if conversion drops existing array entries.</comment>

<file context>
@@ -213,4 +213,21 @@ describe('formDataToJSON', () => {
+
+    // `length` is an own property of the intermediate arrays the parser
+    // builds, so a field named `length` previously hit RangeError.
+    formData.append('metadata[length]', 'long');
+    formData.append('metadata[0]', 'a');
+    formData.append('size[length][unit]', 'cm');
</file context>
Suggested change
formData.append('metadata[length]', 'long');
formData.append('metadata[0]', 'a');
formData.append('metadata[0]', 'a');
formData.append('metadata[length]', 'long');

@jasonsaayman jasonsaayman left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR #11353 - fix(formToJSON): support 'length' as a field name

Repo: axios/axios Author: @princejain756 Base: v1.x Files: 2 **+23/-0
CI: 1 in_progress, 3 success; no build/test workflow result is present in this snapshot. Mergeability: mergeable. Reviewed head: f8f35f01a8e2044a260d3b041c9dc5f8598cab3f.

Repo Profile

Axios is an npm JavaScript HTTP client for browsers and Node, with XHR/Fetch/HTTP adapters, default and named exports, interceptors, headers/errors, and paired ESM/CJS declarations. The target uses Vitest plus browser and package/module tests; v1 packaging covers older Node CJS runtimes as well as current ESM, Bun and Deno. Contributions preserve transport/security boundaries, add regression coverage and prerelease records, and defer unreleased user docs to PRE_RELEASE_DOCS.md. This review uses the actual target-branch guidance and files, not the separate local v0 checkout.

Verdict

Close — A superior proposal covers the same defect without this candidate's drawbacks; see the comparison and scoped closure below.

Change Explanation And User Impact

A FormData field such as metadata[length]=long collides with the special length property of an intermediate array, throwing RangeError during reconstruction. This head converts that array to an ordinary object before descending into a length segment. Executed through axios.formToJSON: the target throws when length and a numeric sibling occur in either order; this head preserves both values. The implementation is materially the same narrow guard as #11296. Its single combined test covers length-first, nested and dotted fields, while #11296 additionally covers reversed ordering, repetitions and the browser HTML-form path.

Validation scope: source/diff and regression-test review. Examples explicitly marked executed used isolated source snapshots on Node 24.18.0 with the workspace dependency installation; these were focused checks, not a clean install, full CI matrix, or full test-suite run. Author-reported test results were not treated as independently executed.

Competing PRs

Search: axios/axios open PRs, including drafts; full open-list scan plus formDataToJSON in:title,body, 11295 in:title,body, credential redaction in:title,body. Complementary searches were run across related APIs/issues; no query reached the 100-result cap and no search failed. The five explicitly excluded PRs were not reviewed or modified in this batch.

#11296 and #11328 address the same length-slot failure. #11296 uses a narrower guard and has both insertion orders plus browser HTML-form coverage, so it is preferred. #11278 preserves empty field names; #11280 supplies a benchmark; #11299 strengthens hardening tests. Those are complementary. Newly opened #11353 uses the same targeted guard as #11296, with fewer regressions and no prerelease entry; its combined length/nested/dotted cases are covered by #11296.

Preferred PR: #11296 retains the targeted guard with both insertion orders, repetition and browser HTML-form coverage.

Unique contributions: Preserve attribution for the independent reproductions in #11328 and #11353. No required unique coverage from either candidate is missing in #11296.

Action: Select #11328 and #11353 for scoped closure in favor of #11296 after final refresh; the retained candidate still requires validation. No closure is claimed here.

Project Fit

North star: Reliable HTTP transport and configuration across supported JavaScript environments, without embedding application-specific policy.

Benefits: Preserves length-named form fields without assigning them to an array length slot.

Tradeoffs: The fix belongs in the parser, but parallel equivalent implementations split the useful regression evidence.

Fit: Strong — The underlying problem belongs in the transport, serializer, declarations or their maintenance tests.

Adversarial Review

Strongest objection: The fix belongs in the parser, but parallel equivalent implementations split the useful regression evidence. Latest-head integration evidence is still needed.

Abuse/failure modes checked: Read the complete diff and linked issue #11295, compared the guard and tests with #11296/#11328, and ran both insertion orders against this head and the current target.

Result: No concrete source defect established in the examined cases; validation and integration limits remain below.

Disposition

Close as duplicate/superseded
Selected for closure, not yet executed at the time of this review. Final closure is conditional on both heads remaining unchanged. Prepared explanation: “Thanks for the contribution. Consolidating this fix in #11296 because its narrower length guard covers both insertion orders and the browser form path. The replacement still needs its own validation before merge.”

Semver

patch — Corrects existing behavior or strengthens internal tooling/tests without adding a public API.

Breaking Changes

None intended beyond the bug correction described above; no public API removal or new runtime requirement is introduced by this diff.

Documentation

This head lacks PRE_RELEASE_CHANGELOG.md. The retained #11296 includes the required prerelease entry.

Performance And Regression Risk

Hot path touched: Yes — request/response processing or its shared helpers.

Performance concern: No unbounded new work identified in the changed path. The fix belongs in the parser, but parallel equivalent implementations split the useful regression evidence.

Regression risk: low — the changed boundary needs regression and integration coverage, particularly after any rebase.

Evidence requested: The latest-head checks listed below; no extra benchmark requested for this scoped change.

Blocking Issues

  • Latest-head build/test validation is unavailable in the returned GitHub checks. Run or attach the repository build, relevant regression suite and required package/type/browser checks before merge; review/security bots alone do not establish that they pass. This is a validation hold, not an invented source defect.

Non-Blocking Suggestions

  • Preserve attribution for the independent reproduction; consolidate on #11296, which already covers the required cases and broader entry-point regressions.

Looks Good

  • Read the complete diff and linked issue #11295, compared the guard and tests with #11296/#11328, and ran both insertion orders against this head and the current target.

@greptile-apps

greptile-apps Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change reaches FormData conversion in a bounded Axios workflow.

The required prerelease entry must be added before merging; the reverse-order regression test is a non-blocking improvement. No current runtime failure was established.

Findings

  1. P2 Required release note is missing ▶
  2. P2 Earlier fields lack test coverage ▶
Fix with agent prompt
### Issue 1
lib/helpers/formDataToJSON.js:127-130
This runtime fix has no entry in `PRE_RELEASE_CHANGELOG.md`. `AGENTS.md` requires a committed prerelease entry for every bug fix; the PR description does not replace it. Add a Bug Fixes entry describing support for fields named `length`, linking #11295 and #11353. This repository requirement must be satisfied before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

### Issue 2
tests/unit/helpers/formDataToJSON.test.js:222-223
The new test appends `metadata[length]` before `metadata[0]`, so it only checks conversion of an empty array. As a non-blocking improvement, add the reverse order and expect the same result. Without that case, the test could still pass if conversion later dropped existing numeric fields.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Fixes formDataToJSON so a field named length does not write to an array's built-in length.

  • FormData parsing stores length fields as ordinary nested keys.

T-Rex validation blocked

Execution completed, but publishing the scripts and captured output was blocked: the session provides no artifact-upload operation, callable collector, authorized destination, or upload credentials. No uploaded artifact references are claimed.

Reviews (1) · Last reviewed commit: "fix(formToJSON): support 'length' as a f..." · Reviewed by Greptile

Comment on lines +127 to +130
if (utils.isArray(target[name]) && path[index] === 'length') {
// An array's own `length` property cannot hold a named field, so the
// intermediate array is converted to an object before descending.
target[name] = arrayToObject(target[name]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Required release note is missing

This runtime fix has no entry in PRE_RELEASE_CHANGELOG.md. AGENTS.md requires a committed prerelease entry for every bug fix; the PR description does not replace it. Add a Bug Fixes entry describing support for fields named length, linking #11295 and #11353. This repository requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: lib/helpers/formDataToJSON.js
Line: 127-130

Comment:
**Required release note is missing**

This runtime fix has no entry in `PRE_RELEASE_CHANGELOG.md`. `AGENTS.md` requires a committed prerelease entry for every bug fix; the PR description does not replace it. Add a Bug Fixes entry describing support for fields named `length`, linking #11295 and #11353. This repository requirement must be satisfied before merging.

**Context Used:** AGENTS.md ([source](https://github.com/axios/axios/blob/v1.x/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +222 to +223
formData.append('metadata[length]', 'long');
formData.append('metadata[0]', 'a');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Earlier fields lack test coverage

The new test appends metadata[length] before metadata[0], so it only checks conversion of an empty array. As a non-blocking improvement, add the reverse order and expect the same result. Without that case, the test could still pass if conversion later dropped existing numeric fields.

TREX Ran code and verified through TREX

Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/unit/helpers/formDataToJSON.test.js
Line: 222-223

Comment:
**Earlier fields lack test coverage**

The new test appends `metadata[length]` before `metadata[0]`, so it only checks conversion of an empty array. As a non-blocking improvement, add the reverse order and expect the same result. Without that case, the test could still pass if conversion later dropped existing numeric fields.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@jasonsaayman

Copy link
Copy Markdown
Member

Thanks @princejain756 for the length-field fix and clear reproduction. I am consolidating this in #11296, which uses the same targeted length guard and includes the cases here plus reversed insertion order, repeated fields, browser HTML-form coverage and a prerelease entry. Closing this equivalent proposal with credit for your independent reproduction. The retained PR still needs its own latest-head validation before merge.

@princejain756

Copy link
Copy Markdown
Author

Thanks for carrying it forward. The extra cases in #11296 (reversed insertion order, repeated fields) look right.

@princejain756

Copy link
Copy Markdown
Author

Both points addressed in 47ee0d3:

16 tests pass in formDataToJSON.test.js.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

formToJSON throws for nested fields named length

2 participants