User Agents

Web browsers and everyday web tech, explained

How to Handle Browser File Downloads with an API

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to make a browser download a file that your API returns, using standard web techniques. You'll learn the two main approaches: direct navigation and using JavaScript's fetch API with a Blob. By the end, you'll be able to trigger downloads for PDFs, images, CSV exports, and more, while handling errors gracefully.

What You'll Need

  • A basic understanding of HTTP requests and responses
  • An API endpoint that returns a file (e.g., /api/download) with appropriate headers
  • A modern web browser (Chrome, Firefox, Safari, Edge)
  • For the fetch approach: basic JavaScript knowledge

Step-by-Step

  1. Understand the server response. The API should return the file with a Content-Disposition: attachment; filename="filename.ext" header. This tells the browser to download instead of display. If the header is missing, the browser may try to render the file inline.
  2. Method 1: Direct navigation (simplest). Use a plain link or window.location to hit the endpoint. When the response has Content-Disposition: attachment, the browser downloads it automatically. Example: <a href="/api/download">Download</a> or window.location.href = '/api/download'.
  3. Method 2: Fetch with Blob (more control). Use fetch() to get the file as a Blob, then create a temporary object URL and click a hidden link. This lets you handle errors, show progress, or add authorization headers. Example:
    fetch('/api/download') .then(res => res.blob()) .then(blob => { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'filename.ext'; document.body.appendChild(a); a.click(); URL.revokeObjectURL(url); a.remove(); });
  4. Handle authentication. If your API requires a token, include it in the request headers. With fetch, add headers: { 'Authorization': 'Bearer ' + token }. Direct navigation can't set headers, so use fetch or include the token in a cookie.
  5. Handle errors. With fetch, check res.ok before converting to blob. If not ok, parse the error JSON or text. For direct navigation, you can't catch errors; consider using fetch for better UX.
  6. Set the filename. Prefer using the Content-Disposition header to set the filename. In the fetch approach, you can read it from the header with res.headers.get('Content-Disposition') and parse it. If you set the download attribute, it overrides the header, so be careful.
  7. Clean up the object URL. Always call URL.revokeObjectURL(url) after the download starts to free memory. Do it in a setTimeout or after a small delay, because some browsers need the URL to exist briefly.

Common Mistakes

  • Forgetting the Content-Disposition header on the server—the browser may display the file instead of downloading.
  • Using window.open() for downloads—popup blockers may block it, and it's unreliable.
  • Not handling CORS—if your API is on a different domain, you need CORS headers and the fetch request must be allowed.
  • Setting the download attribute on a cross-origin link—it's ignored for security reasons.
  • Calling URL.revokeObjectURL too early, which can break the download in some browsers.

Tips

  • For large files, show a loading indicator while fetching.
  • Use response.blob() for binary files; for text like CSV, you can use response.text() and create a Blob with the correct MIME type.
  • Test with different file types (PDF, ZIP, image) to ensure your code works universally.
  • If you need to support older browsers, consider using XMLHttpRequest as a fallback, but modern browsers all support fetch.
  • Always sanitize the filename from the header to avoid path traversal issues.

Troubleshooting

  • Download doesn't start: Check the browser's network tab. If the response has a Content-Disposition header, it should download. If not, add it on the server.
  • File downloads as 'download' or without extension: The Content-Disposition filename may be missing or malformed. Ensure it's properly encoded (e.g., filename*=UTF-8''name%20with%20spaces.pdf).
  • Fetch fails with CORS error: The server must include Access-Control-Allow-Origin and allow the required methods and headers. If you need to send credentials, set credentials: 'include' and the server must echo specific headers.
  • Blob downloads as a text file: The MIME type in the Blob is incorrect. Set it explicitly: new Blob([data], { type: 'application/pdf' }).
  • Download works but file is corrupted: If you're using fetch and the response is compressed (e.g., gzip), the browser should decompress automatically. If you manually set headers, ensure you don't override Accept-Encoding.

Frequently Asked Questions

Can I use a simple link for authenticated downloads?

Yes, if the authentication is cookie-based. If you use token-based auth in headers, you must use fetch or XMLHttpRequest to set the header.

How do I download a file that requires a POST request?

Use fetch with method POST. The response can still be a Blob. Example: fetch('/api/export', { method: 'POST', body: JSON.stringify(data) }) then handle the blob as above.

Why does my download open in a new tab instead of downloading?

This happens when the server doesn't send Content-Disposition: attachment. Check the response headers and add it.

Can I show a progress bar for downloads?

With fetch, you can read the Content-Length header and use the ReadableStream to track progress, but it's complex. For simplicity, use a library like axios with onDownloadProgress.

Is it safe to use URL.createObjectURL?

Yes, but always revoke the URL after the download to avoid memory leaks. Also, be careful with large files as they are held in memory.

What if the API returns an error JSON instead of a file?

In fetch, check res.ok. If false, parse the JSON and show an error message. For direct navigation, you can't detect this; use fetch for better error handling.