> For the complete documentation index, see [llms.txt](https://triton.pharos.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://triton.pharos.ai/beyond-apex/lwc-and-apex.md).

# LWC and Apex

Correlate a front-end action with the Apex it triggers — pass the transaction id from LWC into your controller so UI logs and server logs land in one trace.

Most interesting bugs live in the seam between the browser and the server. A user clicks a button, the component calls Apex, the Apex does a DML that blows up — and you're left correlating a front-end error with a back-end one by squinting at timestamps. Triton removes the squinting: pass one transaction id across the boundary and both sides log into the same tree.

The setup: a button click starts the flow in LWC, then hands off to Apex. Our job is to link the two.

## The LWC controller

Start a log on the front end, then call Apex — passing `this.triton.transactionId` so the server can adopt it.

{% code title="logDemo.js" lineNumbers="true" %}

```javascript
import apexActionThatGeneratesDMLError from '@salesforce/apex/LogDemoController.apexActionThatGeneratesDMLError';
import Triton, { AREA, TYPE } from 'c/triton';

export default class LogDemo extends LightningElement {
    triton;
    startTime;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('logDemo');
    }

    handleClick() {
        this.startTime = performance.now();
        this.executeScenario();
    }

    async executeScenario() {
        // Log the start of the flow on the front end
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('LWC action - DML Error')
                .details('Execution start')
                .duration(performance.now() - this.startTime)
        );

        try {
            // Hand the transaction id to Apex so its logs correlate
            await apexActionThatGeneratesDMLError({
                transactionId: this.triton.transactionId
            });
        } catch (error) {
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}
```

{% endcode %}

The key line is `transactionId: this.triton.transactionId`. That's the current front-end transaction id, going along for the ride.

## The Apex controller

On the server, `Triton.resumeTransaction(transactionId)` adopts the id, so every Apex log joins the same tree the LWC logs started:

{% code title="LogDemoController.cls" lineNumbers="true" %}

```apex
public with sharing class LogDemoController {

    @AuraEnabled
    public static void apexActionThatGeneratesDMLError(String transactionId) {
        // Adopt the transaction id passed from LWC
        Triton.resumeTransaction(transactionId);

        Triton.debug(Triton.t
            .type(TritonTypes.Type.Backend)
            .area(TritonTypes.Area.Community)
            .summary('LWC controller (apex) - DML Error')
            .details('Apex execution start'));

        try {
            ContentVersion cv = new ContentVersion();
            cv.ContentLocation = 'Apex Error';
            cv.Title = 'Apex Error';
            cv.PathOnClient = 'ApexError.pdf';
            insert cv;   // throws a DMLException
        } catch (Exception e) {
            Triton.error(Triton.t.area(TritonTypes.Area.Community).exception(e));
        }

        Triton.flush();
    }
}
```

{% endcode %}

`Triton.resumeTransaction(...)` is the whole trick — without it, the Apex logs would form their own separate trace. The buffered `debug` and `error` logs publish together on the closing `Triton.flush()`.

## The result

One click, four logs, one transaction:

* **Parent** — LWC **Debug** log from `executeScenario()`
  1. Child Apex **Debug** log from `apexActionThatGeneratesDMLError()`
  2. Child Apex **Error** log from the try/catch
  3. Child LWC **Error** log from the front-end error handler

{% hint style="info" %}
Everything is stitched together by the shared transaction id. You started it on the front end and resumed it on the back end — that's all correlation requires.
{% endhint %}

## With `@wire`

The same stitching idea applies when Apex is called from a wire: put `transactionId` in the wire config so the server can `resumeTransaction`. Wires need a reactive property for the id — set it in the constructor when you bind Triton (wires can fire before `connectedCallback`).

### LWC side

{% code title="orderBuilder.js" lineNumbers="true" %}

```javascript
import { LightningElement, api, wire } from 'lwc';
import getOrderItems from '@salesforce/apex/OrderBuilderController.getOrderItems';
import Triton, { AREA, TYPE, LEVEL } from 'c/triton';

export default class OrderBuilder extends LightningElement {
    @api recordId;

    /** Wired Apex result so it may be programmatically refreshed. */
    @wire(getOrderItems, { orderId: '$recordId', transactionId: '$_transactionId' })
    wiredOrderItems;

    triton; // Triton instance for logging
    _transactionId; // Direct property for wire reactivity

    constructor() {
        super();
        this.triton = new Triton().bindToComponent('orderBuilder');
        this._transactionId = this.triton.transactionId;

        this.triton.setTemplate(
            this.triton.makeBuilder()
                .level(LEVEL.INFO)
                .type(TYPE.FRONTEND)
                .area(AREA.COMMUNITY)
        );
    }
}
```

{% endcode %}

The reactive `_transactionId` is what makes the wire re-evaluate with the current front-end transaction id. Without it in the config, Apex has nothing to resume.

### Apex side

{% code title="OrderBuilderController.cls" lineNumbers="true" %}

```apex
@AuraEnabled(Cacheable=true)
public static Order_Item__c[] getOrderItems(Id orderId, String transactionId) {
    Triton.resumeTransaction(transactionId);

    Triton.setTemplate(template);

    Triton.info(Triton.t
            .summary('Fetching order items')
            .details('Order ID: ' + orderId)
            .relatedObjects(new List<String>{orderId})
    );

    try {
        Order_Item__c[] orderItems = [
            SELECT
                Id,
                Qty_S__c,
                Qty_M__c,
                Qty_L__c,
                Price__c,
                Product__r.Name,
                Product__r.MSRP__c,
                Product__r.Picture_URL__c
            FROM Order_Item__c
            WHERE Order__c = :orderId
            WITH USER_MODE
        ];

        Triton.debug(Triton.t
                .summary('Order items fetched successfully')
                .details('Total order items retrieved: ' + orderItems.size())
                .relatedObjects(new List<String>{orderId})
        );

        Triton.flush();
        return orderItems;

    } catch (Exception e) {
        Triton.logNow(Triton.t
                .summary('Error fetching order items')
                .details('Order ID: ' + orderId)
                .exception(e)
                .relatedObjects(new List<String>{orderId})
        );
        throw e;
    }
}
```

{% endcode %}

Same trick as the imperative example: `Triton.resumeTransaction(transactionId)` adopts the LWC id before any logging. (`Cacheable=true` is normal for `@wire`; if you were tempted to stitch via Platform Cache instead, see the caveat on [Platform Cache for Transactions](https://triton.pharos.ai/beyond-apex/lwc-and-apex-cache.md#wont-work-with-cacheable-apex--wire).)

Passing the id through a method parameter is the explicit, predictable approach — great when the call graph is simple. When it isn't (multiple components, async hops, no clean place to thread a parameter), Platform Cache can carry the id for you. That's next: [Platform Cache for Transactions](https://triton.pharos.ai/beyond-apex/lwc-and-apex-cache.md). For the complete cross-technology journey, see [End-to-End Logging](https://triton.pharos.ai/end-to-end.md).
