fix(utils): handle `null` in isJSONSerializable by MFA-G · Pull Request #599 · unjs/ofetch · GitHub
Skip to content

fix(utils): handle null in isJSONSerializable#599

Open
MFA-G wants to merge 1 commit into
unjs:mainfrom
MFA-G:fix/json-serializable-null
Open

fix(utils): handle null in isJSONSerializable#599
MFA-G wants to merge 1 commit into
unjs:mainfrom
MFA-G:fix/json-serializable-null

Conversation

@MFA-G

@MFA-G MFA-G commented Jun 25, 2026

Copy link
Copy Markdown

Summary

isJSONSerializable(null) currently throws:

TypeError: Cannot read properties of null (reading 'buffer')

null falls through every early branch and reaches the value.buffer check (src/utils.ts line 31), where reading a property off null throws.

There is also a dead-code branch: typeof value can never return null, so the t === null part of the primitive check on line 22 never matches.

Changes

  • Add an explicit value === null early return. null is JSON serializable (JSON.stringify(null) === "null"), so it returns true.
  • Remove the dead t === null condition from the primitive check.
  • Add test/utils.test.ts with unit tests for isJSONSerializable covering null, undefined, primitives, plain objects, toJSON objects, arrays, and non-serializable values (functions, symbols, bigint, typed arrays, FormData, URLSearchParams).

Validation

  • pnpm lint passes (eslint + prettier).
  • vitest run passes (34 tests, including the 6 new ones).
  • Confirmed the new null test fails against the current code (reproduces the TypeError) and passes with this fix.

Closes #571

Summary by CodeRabbit

  • Bug Fixes

    • Corrected JSON serializability checks so null is now treated as serializable.
    • Improved handling of values that should not be considered JSON-safe, reducing incorrect results.
  • Tests

    • Added coverage for serializable and non-serializable values.
    • Verified support for null, objects, arrays, and toJSON-based values, along with rejection of unsupported types.

`isJSONSerializable(null)` threw `TypeError: Cannot read properties of
null (reading 'buffer')` because `null` fell through to the
`value.buffer` check. Also `typeof value` never returns `null`, so the
`t === null` branch was dead code.

`null` is JSON serializable (`JSON.stringify(null) === "null"`), so it now
returns `true` via an explicit early check. Added unit tests for
isJSONSerializable covering null, undefined, primitives, plain objects,
toJSON objects, and non-serializable values.

Closes unjs#571
@coderabbitai

coderabbitai Bot commented Jun 25, 2026

Copy link
Copy Markdown

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.

isJSONSerializable bug

1 participant