Downloading files using standard tags is straightforward, but it lacks the ability to send custom request headers, such as tokens for protected files. To bypass this, you must use an AJAX-based approach (Fetch, Axios, or XMLHttpRequest) to retrieve the file data as a Blob and then programmatically trigger a download. Using the Fetch API (Modern Standards)
Use URL.createObjectURL to turn the blob into a temporary browser link.
Axios simplifies the process by handling some of the boilerplate and providing a consistent API for both browser and Node.js.
Request the file with your custom headers and set the response type to a blob.
The Fetch API is the standard modern method for making network requests. It allows you to define a headers object to include any necessary metadata.
async function downloadWithFetch(url, token, filename) { const response = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, 'Custom-Header': 'value' } }); const blob = await response.blob(); const downloadUrl = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = downloadUrl; a.download = filename; document.body.appendChild(a); a.click(); // Cleanup window.URL.revokeObjectURL(downloadUrl); a.remove(); } Use code with caution. Using Axios (Library Approach)