Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

A file download with React Query fails when you call createObjectURL

ErrorTypeError when calling URL.createObjectURL with the data from useQuery or useMutation

Short answer

URL.createObjectURL only accepts a Blob or a MediaSource. If your query function returns parsed JSON, text, a fetch Response or a wrapper object, the call fails or the saved file is garbage. Make the request return a Blob (responseType blob in axios, response.blob() in fetch), read the body once, then create and revoke the object URL.

  • Applies to React 19, @tanstack/react-query 5, axios 1.x, Chrome 130+
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Log what the query function really returns. A download only works when it is a Blob; anything else explains the error.

    const { data } = useQuery({ queryKey: ['report'], queryFn: fetchReport, enabled: false });
    console.log(data instanceof Blob, typeof data, data);
  2. 2Match what you see, then jump to its fix

    1. 1data is a string or a plain object, and data instanceof Blob is falseaxios parsed the body instead of returning a BlobFix
    2. 2data is a Response, or the query function ends with return res or res.json()With fetch, the Response object was returned instead of its BlobFix
    3. 3TypeError after a first successful read of the same responseThe body was already read onceFix
    4. 4The query returns a Blob, but the failing call passes something around it, such as the whole query resultThe wrong thing is passed to createObjectURLFix

What does the error look like?

  • TypeError when calling URL.createObjectURL with the data from useQuery or useMutation
  • The downloaded file is a few bytes long or opens as text
  • data is an object or a string, not a Blob

Cause 1 of 4

axios parsed the body instead of returning a Blob

1Check

axios decides how to read the body from responseType. Without it, the body is not handed back as a Blob. The documented values include arraybuffer, json, text, stream and blob (blob is browser only).

grep -rn "responseType" src/

2Fix

Ask for a Blob on the request and return it from the query function.

const fetchReport = async () => {
  const res = await axios.get('/api/report', { responseType: 'blob' });
  return res.data; // a Blob
};

3Verify

The log from the first step now prints true for instanceof Blob.

console.log(data instanceof Blob, data.type, data.size);

Confirmed by axios.rest

Did this fix it?

Cause 2 of 4

With fetch, the Response object was returned instead of its Blob

1Check

Response.blob() reads the stream to the end and resolves with a Blob whose type comes from the Content-Type header. Returning the Response itself, or calling json() on a file, gives createObjectURL the wrong type.

grep -n "res.json()\|response.json()\|return res" src/api/*.ts

2Fix

Call blob() on the response and return that.

const fetchReport = async () => {
  const res = await fetch('/api/report');
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.blob();
};

3Verify

Create the object URL from the returned data and open it.

const url = URL.createObjectURL(data);
window.open(url);

Confirmed by developer.mozilla.org

Did this fix it?

Cause 3 of 4

The body was already read once

1Check

A response body can be read only once. blob() throws a TypeError when the body is disturbed or locked, for example after an earlier json() or text() call, a logging line or an interceptor that already consumed it.

grep -rn "\.text()\|\.json()\|\.clone()" src/

2Fix

Read the body exactly once. If something else must read it too, call clone() before the first read.

const res = await fetch('/api/report');
const copy = res.clone();
console.log(copy.status);
return res.blob();

3Verify

The download runs without a TypeError.

console.log('size', data.size);

Confirmed by developer.mozilla.org

Did this fix it?

Cause 4 of 4

The wrong thing is passed to createObjectURL

1Check

createObjectURL takes a Blob, a File or a MediaSource and returns a URL string. Passing the useQuery result object, or data while it is still undefined, fails.

grep -rn "createObjectURL" src/

2Fix

Pass the data value, and call it only once it exists, for example in onClick after refetch resolves.

const { refetch } = useQuery({ queryKey: ['report'], queryFn: fetchReport, enabled: false });

async function onDownload() {
  const { data } = await refetch();
  if (!data) return;
  const url = URL.createObjectURL(data);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'report.pdf';
  a.click();
  URL.revokeObjectURL(url);
}

3Verify

Click the button and check that the browser saves the file with the right name.

console.log('clicked');

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Keep one download helper that returns a Blob, so no component parses the body itself.
  • Call URL.revokeObjectURL after the download starts; the docs say to release an object URL this way.
  • Check res.ok before reading the body, so an error page is not saved as the file.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.