A file download with React Query fails when you call createObjectURL
TypeError when calling URL.createObjectURL with the data from useQuery or useMutationShort 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.
Fix it fast
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);2Match what you see, then jump to its fix
- 1
data is a string or a plain object, and data instanceof Blob is falseaxios parsed the body instead of returning a BlobFix - 2
data 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
TypeError after a first successful read of the same responseThe body was already read onceFix - 4
The query returns a Blob, but the failing call passes something around it, such as the whole query resultThe wrong thing is passed to createObjectURLFix
- 1
What does the error look like?
TypeError when calling URL.createObjectURL with the data from useQuery or useMutationThe downloaded file is a few bytes long or opens as textdata 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
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/*.ts2Fix
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
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
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
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:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Astro Code component fails inside a React component
Astro components cannot be rendered directly via function call
Astro components such as Code only exist on the server and render static HTML.
2 causes, each with a fixWeb apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
How to catch and handle a 422 from Axios in a Redux thunk
action.error.message is 'Rejected' and action.payload is undefined
A 422 means the server read the request but cannot process its content, so repeating it unchanged fails again.
4 causes, each with a fixWeb apps
axios gets 429 Too Many Requests from a React app
429 (Too Many Requests)
A 429 comes from the server or an API gateway, not from axios: your client sent too many requests in a window.
4 causes, each with a fixWeb apps
Axios request is not cancelled when a React component unmounts
A cancelled request is logged as an error in the catch block
Axios cancels a request when you pass it an AbortSignal and later call abort() on its controller.
4 causes, each with a fix