title: Download large file with authorization headers
body: <p>In my React app, I want to have a button to download a file that behaves identical to a <code>&lt;a href=&quot;...&quot; download /&gt;</code> link:</p>
  <ul>
  <li>When clicking on it, the user gets asked immediately whether to download or open the file (before the download starts)</li>
  <li>The download progress is shown in the browser download list</li>
  <li>The download can be streamed to disk immediately, without filling up the browser memory so it works for large files as well</li>
  <li>I need to pass in a <code>Bearer</code> token in the header (which is the reason I cannot use the <code>&lt;a href download/&gt;</code> approach)</li>
  </ul>
  <p>The solution I find online is using</p>
  <pre><code>fetch(... including the bearer token in the header)
  .then(res =&gt; res.blob() )
  .then(data =&gt; {
    const link = document.createElement(&quot;a&quot;);
    link.href = window.URL.createObjectURL(new Blob([data], { type: &quot;application/octet-stream&quot; }));
    link.download = fileName;
    document.body.append(link);
    link.click();
    window.URL.revokeObjectURL(link.href);
  });
  </code></pre>
  <p>but this has 2 obvious drawbacks:</p>
  <ul>
  <li>The user only gets to see the &quot;download or open&quot; dialog after the file has downloaded. For large files where the download takes a while, it simply looks like nothing is happening after clicking</li>
  <li>For downloads that don't fit into the memory of the browser, it crashes.</li>
  </ul>
  <p>I also saw the <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads/download" rel="nofollow noreferrer"><code>downloads.download()</code></a> API but that doesn't work in Safari yet so I didn't try it as I need to support all major browsers.</p>
  <p>The last option (that I didn't explore in detail) is using the <code>fetch().then(res =&gt; res.body)</code> and do something with the stream. It would allow me to stream the download directly to a file, but I fail to see how I would ever show the &quot;download or open&quot; dialog to the user, and how to get access to the file location the user chooses for the download.</p>
  <p>Having a button to download a (large) file in a React app doesn't sound like a far fetched requirement, so I'm probably overlooking something trivial. Can somebody point me in the right direction ?</p>