Skip to content

Bug: auto-generated IDs can be purely numeric strings, causing query failures due to strict type checking #1734

@asagi820

Description

@asagi820

Describe the bug

In json-server@1.0.0-beta.6 and later, query parameters consisting entirely of digits are coerced into Number types for strict equality checking.

However, the randomId() function (src/random-id.ts) uses randomBytes(2).toString('hex'). There is an approximate 15% chance that a generated 4-character hex string will consist entirely of digits (e.g., "1234", "8092").

When this happens, the newly created item cannot be queried via URL parameters.
For example, querying ?id=1234 will coerce the query to a Number 1234, which strictly does not match the stored String "1234".

Steps to reproduce

  1. Run json-server (version >= 1.0.0-beta.6).
  2. POST multiple new items to an endpoint until one is assigned an ID containing only digits (e.g., "id": "4952").
  3. Attempt to GET that item using a query parameter: /items?id=4952.
  4. The server returns an empty array [].

Expected behavior

The server should return the item that has the auto-generated string ID "4952".

Actual behavior

The server returns [] because the query parameter is parsed as the Number 4952, and 4952 !== "4952".

Possible Solution

  1. Modify randomId() to ensure it always contains at least one letter (e.g., prefixing with a character like "id-" + randomBytes(2).toString('hex')).
  2. Or, adjust the query parsing logic to handle string/number fallbacks for IDs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions