When building enterprise features in Salesforce Lightning Web Components (LWC), exporting data as a downloadable file is a frequent requirement. Whether you need to export record payloads, configuration settings, or integration logs, generating and downloading JSON files directly in the browser improves user experience without heavy server overhead.
Blob object, and triggering a virtual anchor (<a>) tag click.
Prerequisites
- Basic understanding of LWC structure and JavaScript ES6 syntax.
- Familiarity with standard browser Web APIs like
BlobandURL.createObjectURL().
Method 1: Generating and Downloading In-Memory JSON Data
If your component already holds data in client-side memory, you can convert it to JSON and prompt an immediate download using a dynamic anchor element.
- Serialize the JavaScript object using
JSON.stringify(). - Create a new
Blobinstance withtype: 'application/json'. - Generate a temporary object URL via
URL.createObjectURL(). - Programmatically click a hidden anchor element with the
downloadattribute set. - Clean up the URL reference using
URL.revokeObjectURL()to prevent memory leaks.
// downloadJSONExample.js
import { LightningElement } from 'lwc';
export default class DownloadJSONExample extends LightningElement {
downloadJSONFile() {
const jsonData = {
appName: 'Salesforce LWC Export',
timestamp: new Date().toISOString(),
records: [
{ id: '001XXXXXXXXXXXX1', name: 'Acme Corp' },
{ id: '001XXXXXXXXXXXX2', name: 'Global Tech' }
]
};
const jsonString = JSON.stringify(jsonData, null, 2);
const blob = new Blob([jsonString], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'export-data.json';
link.click();
// Release URL object reference from memory
URL.revokeObjectURL(url);
}
}
Bind the method to a button in your template HTML file:
<!-- downloadJSONExample.html -->
<template>
<lightning-card title="Export Data" icon-name="utility:download">
<div class="slds-m-around_medium">
<lightning-button
label="Download JSON"
variant="brand"
icon-name="utility:download"
onclick={downloadJSONFile}>
</lightning-button>
</div>
</lightning-card>
</template>
Method 2: Fetching JSON from an Endpoint and Downloading
When the target JSON file resides on a remote server or REST endpoint, retrieve it asynchronously using fetch() and execute the same file download workflow once the payload resolves.
// downloadJSONFetchExample.js
import { LightningElement } from 'lwc';
export default class DownloadJSONFetchExample extends LightningElement {
async downloadRemoteJSON() {
try {
const response = await fetch('https://api.example.com/data-endpoint');
if (!response.ok) {
throw new Error('Failed to fetch file content');
}
const jsonData = await response.json();
const jsonString = JSON.stringify(jsonData, null, 2);
const blob = new Blob([jsonString], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'remote-data.json';
link.click();
URL.revokeObjectURL(url);
} catch (error) {
console.error('Error downloading JSON:', error);
}
}
}
URL.revokeObjectURL(url) keeps generated Blob references active in browser memory. Always release created object URLs after initiating file downloads.
- Core Method: Combine
JSON.stringify(),Blob, andURL.createObjectURL(). - MIME Type: Explicitly declare
{ type: 'application/json' }when initializing the Blob. - Trigger Mechanism: Instantiate an in-memory
<a>element, assigndownloadandhrefproperties, and invoke.click(). - Cleanup: Call
URL.revokeObjectURL()immediately after triggering the click event.
Conclusion
Exporting JSON files directly from Lightning Web Components provides a smooth data export mechanism for Salesforce users. By combining native Web APIs like Blob and URL.createObjectURL(), you can build reliable file download functionality without writing server-side file management logic.