Skip to content

trackOpen() fails with "JSON Parse error: Unexpected character: o" on React Native due to fetch polyfill auto-parsing #3

@dbezrukov

Description

@dbezrukov

Description

The trackOpen() method fails on React Native with JSON Parse error: Unexpected character: o even when the API returns a valid JSON response with clickId.

Root Cause

React Native's fetch polyfill automatically parses JSON responses when content-type: application/json is present. When the SDK calls response.json() in trackOpen(), the response body is already a parsed JavaScript object, not a string. Calling .json() on an already-parsed object causes it to be implicitly converted to "[object Object]", which then fails JSON parsing with "Unexpected character: o".

Reproduction

  1. Install @dub/react-native in a React Native app
  2. Initialize with dub.init({ publishableKey, domain })
  3. Copy a valid Dub link to clipboard (e.g., https://go.customuse.com/test)
  4. Call dub.trackOpen() on first launch
  5. Observe the error: JSON Parse error: Unexpected character: o

Evidence

Direct API call using XMLHttpRequest with responseType = 'text' works correctly:

// This works - returns valid JSON with clickId
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.dub.co/track/open', true);
xhr.responseType = 'text';
xhr.onload = () => {
  const data = JSON.parse(xhr.responseText); // ✅ Works
  console.log(data.clickId); // "MT3ka2lKYidkICLm"
};

Suggested Fix

Option 1: Use XMLHttpRequest with responseType = 'text' instead of fetch
Option 2: Check if the response body is already an object before calling .json()

const response = await fetch(url, options);
const body = await response.text();
return typeof body === 'object' ? body : JSON.parse(body);

Environment

@dub/react-native: 0.0.2
React Native: 0.76.x
Platform: iOS (likely affects Android too)
Expo SDK: 52

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions