node-fetch icon indicating copy to clipboard operation
node-fetch copied to clipboard

fix: TypeError: Cannot read properties of undefined (reading 'body') …

Open Pruthvik-P opened this issue 8 months ago • 0 comments

fix: guard against undefined request/options in redirect step (fixes #1845)

Purpose

Prevent a runtime crash in the redirect-follow logic when either the internal request instance or options_ object is ever undefined. Without this guard, calling fetch() on certain redirect sequences (e.g. 308 → 302 with a stream body) throws

Changes

  • In src/index.js, changed the redirect-step-9 guard to use optional chaining (request?.body and options_?.body) rather than assuming those objects always exist.
  • Rebuilt the dist/ bundle so the distributed code includes this guard.
  • Manually verified with an Express-based repro (308 → 302 → 200) that:
    • Before patch: crash on second redirect
    • After patch: follows redirects correctly and logs “Done”

Additional information

I did not add unit tests in this PR—but I can follow up with a mocha/jest test if you'd like. Manual repro code is in test/manual/redirect-repro.js (feel free to move it or convert it into an automated test suite).


Checklist

  • [x] I updated documentation if necessary
  • [x] I added a unit test (or will follow up in a separate PR)

  • fixes #1845

Pruthvik-P avatar May 01 '25 18:05 Pruthvik-P