Sub topic 10
Building a headless action
This chapter assumes you can build a Lightning web component (HTML template, JavaScript class, js-meta.xml) and use @api and event dispatching. It also assumes you have used a Salesforce DX project to deploy metadata, and that you know what a page layout is. The earlier chapters on screen actions covered lightning-quick-action-panel and CloseActionScreenEvent. A headless action uses neither.
What "headless" means
A headless action is a quick action with no user interface of its own. The user clicks the action button, and the platform runs your code. No modal opens, and nothing renders. Use one when the work needs no input from the user. Typical examples are:
- Setting a field to a fixed value, such as marking a record as reviewed.
- Calling an Apex method and reporting the result in a toast.
- Navigating to another page.
- Starting a process that needs only the record ID.
If you need to collect input, show a preview, or ask for confirmation, build a screen action instead.
How the platform runs it
The platform creates your component, sets recordId, and then calls the public invoke() method. Your code runs in invoke().
Two points follow from this sequence.
recordIdis available insideinvoke(). You do not need to wait for it.- No panel exists, so there is nothing to close.
CloseActionScreenEventhas no role here.
The metadata file
The only difference from a screen action in js-meta.xml is the actionType value. Use Action instead of ScreenAction.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>Action</actionType>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>The target is still lightning__RecordAction. The actionType is what tells the platform to call invoke() rather than open a panel.
The smallest headless action
The JavaScript class needs recordId and an invoke() method, both marked @api.
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class NotifyRecord extends LightningElement {
@api recordId;
@api invoke() {
this.dispatchEvent(new ShowToastEvent({
title: 'Action ran',
message: 'Record ' + this.recordId + ' was processed',
variant: 'success'
}));
}
}You do not need an HTML file. A headless bundle can contain just the .js file and the .js-meta.xml file. If you add a template anyway, the platform never shows it.
The invoke name is fixed. If you misspell it or leave off @api, the platform cannot find it. The click then does nothing, and no error appears in the UI.
A more realistic example
Most headless actions change data. This one sets an account's rating to Hot. It uses updateRecord from lightning/uiRecordApi with fields imported from the schema, the same pattern as the screen action.
import { LightningElement, api } from 'lwc';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import ID_FIELD from '@salesforce/schema/Account.Id';
import RATING_FIELD from '@salesforce/schema/Account.Rating';
export default class MarkAccountHot extends LightningElement {
@api recordId;
isRunning = false;
@api async invoke() {
if (this.isRunning) {
return;
}
this.isRunning = true;
const fields = {};
fields[ID_FIELD.fieldApiName] = this.recordId;
fields[RATING_FIELD.fieldApiName] = 'Hot';
try {
await updateRecord({ fields });
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Account rated Hot',
variant: 'success'
}));
} catch (error) {
this.dispatchEvent(new ShowToastEvent({
title: 'Error updating record',
message: error?.body?.message || 'Unknown error',
variant: 'error'
}));
} finally {
this.isRunning = false;
}
}
}Several details matter here.
- The
isRunningguard. A headless action gives the user no visible busy state. Nothing is disabled while the save runs, so a second click can start a second call. The guard drops the extra call. - The
try/catch. With no panel, a failure is invisible unless you report it. An unhandled rejection ininvoke()leaves the user believing the action worked or did nothing at all. Always show an error toast. - The
finallyblock. It resets the flag even when the save fails, so the user can retry. - Field imports. Importing
Account.Ratingthrough@salesforce/schemamakes the deployment fail if the field is deleted, which is better than a runtime error.
Does the record page update?
updateRecord goes through Lightning Data Service. Other components on the page that use LDS (record forms, getRecord wires) pick up the change without extra work.
Changes made outside LDS are different. If invoke() calls an Apex method that updates the record, LDS does not know about it. Call notifyRecordUpdateAvailable from lightning/uiRecordApi to refresh the cache:
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
// After the Apex call resolves:
await notifyRecordUpdateAvailable([{ recordId: this.recordId }]);Using Apex from a headless action
Apex is the usual choice when the work touches several records or needs server logic. The pattern is the same as for any imperative Apex call. Import the method, await it inside invoke(), and handle both outcomes.
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
import closeStaleCases from '@salesforce/apex/CaseActions.closeStaleCases';
export default class CloseStaleCases extends LightningElement {
@api recordId;
@api async invoke() {
try {
const count = await closeStaleCases({ accountId: this.recordId });
await notifyRecordUpdateAvailable([{ recordId: this.recordId }]);
this.dispatchEvent(new ShowToastEvent({
title: 'Done',
message: count + ' cases closed',
variant: 'success'
}));
} catch (error) {
this.dispatchEvent(new ShowToastEvent({
title: 'Could not close cases',
message: error?.body?.message || 'Unknown error',
variant: 'error'
}));
}
}
}The Apex class must have a @AuraEnabled method named closeStaleCases that takes an accountId parameter. This chapter does not cover writing it.
Creating the action and adding it to a layout
The steps are the same as for a screen action.
- Deploy the bundle to your org.
- In Setup, open Object Manager, choose the object, and open Buttons, Links, and Actions.
- Click New Action. Set Action Type to Lightning Web Component, choose your component, and enter a label and name.
- Open Page Layouts, or the Lightning record page, and add the action under Salesforce Mobile and Lightning Experience Actions.
A headless action does not appear in the list until its js-meta.xml has isExposed set to true, the lightning__RecordAction target, and actionType set correctly.
Testing with Jest
You can test invoke() directly, because it is an ordinary public method. Create the element, set recordId, append it to the DOM, and call invoke(). Listen for the toast event on the host element.
import { createElement } from 'lwc';
import NotifyRecord from 'c/notifyRecord';
import { ShowToastEventName } from 'lightning/platformShowToastEvent';
describe('c-notify-record', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('dispatches a success toast when invoked', () => {
const element = createElement('c-notify-record', { is: NotifyRecord });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
const handler = jest.fn();
element.addEventListener(ShowToastEventName, handler);
element.invoke();
expect(handler).toHaveBeenCalledTimes(1);
const detail = handler.mock.calls[0][0].detail;
expect(detail.variant).toBe('success');
expect(detail.message).toContain('001000000000001AAA');
});
});For the updateRecord version, mock lightning/uiRecordApi with jest.mock and make updateRecord resolve or reject. Then await a resolved promise before asserting. Test the failure path as well, because that is where headless actions most often go wrong.
Common pitfalls
| Symptom | Likely cause |
|---|---|
| Clicking the action does nothing | `invoke` is missing, misspelled, or not decorated with `@api` |
| The action opens an empty panel or fails to load | `actionType` is `ScreenAction` instead of `Action` |
| `recordId` is `undefined` | The action was added to a global context, or the code reads it in the constructor |
| The page shows old values after the action | The data changed through Apex and no refresh was requested |
| Two saves happen after a quick double click | No in-progress guard in `invoke()` |
| The user sees no result | No toast, or errors are swallowed |
Exercise
A headless quick action is added to the Account page layout. Users click it and nothing happens, and the browser console shows no error. The JavaScript class has @api recordId; and a method invoke() { ... } without a decorator. What is wrong, and what is the fix?
Show answer
The invoke() method is not public. Without @api, the platform cannot call it, so the click has no effect. Add the decorator so the method reads @api invoke() { ... }. Also confirm that js-meta.xml has <actionType>Action</actionType>.
Exercise
Your headless action calls an Apex method that updates the current Account. After the toast appears, the record page still shows the old values. Why does this happen with Apex but not with updateRecord, and how do you fix it?
Show answer
updateRecord goes through Lightning Data Service, which updates its own cache and notifies the components that use it. An Apex update bypasses LDS, so the cache is stale. Call notifyRecordUpdateAvailable([{ recordId: this.recordId }]) from lightning/uiRecordApi after the Apex call resolves.