Download a file with JavaScript

javascript

Updated August 29, 2026

For data already in the browser, create a Blob, point a temporary link at it, click the link, and release the object URL:

function downloadText(filename, text) {
  const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.append(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(url);
}

For a server response, use a normal authenticated request and let the server send a suitable Content-Disposition header. Check the response status before turning it into a blob, and do not trust a filename supplied by untrusted input. Large files are usually better streamed by the server than assembled in browser memory.

A download attribute can be affected by cross-origin rules and browser policy. Test keyboard access and provide a visible link or button with a useful label instead of triggering an unexplained download on page load.

Sources

related.

Ruslan Osipov

Ruslan Osipov

About the author