Skip to content
Last updated

AppBridge Communication

The AppBridge is a crucial component provided by the @jtl-software/cloud-apps-core package. Its primary function is to establish a secure and reliable communication channel between your app's frontend (running within an Iframe) and the host JTL cloud service environment (e.g., JTL-Wawi).

This bridge allows your app to interact with the host environment, request data (like session tokens), and trigger actions specific to the context it's running in.

AppBridge Interface

The AppBridge class provides the following methods:

export default class AppBridge {
    constructor(messagePort: MessagePort);
    // Listen for specific events from the host environment and execute the callback when they occur
    subscribe(event: string, callback: (data: unknown) => Promise<unknown>): void;
    
    // Send data to the host environment under a specific topic, notifying it about actions or state changes
    publish<TPayload>(topic: string, payload: TPayload): Promise<void>;
    
    // Make a app function available to be called directly by the host environment
    exposeMethod<TMethod>(methodName: string, method: TMethod): void;
    
    // Check if a specific function has already been exposed to the host environment
    isMethodExposed(methodName: string): boolean;
    
    // Invoke functions provided by the host environment to execute host-specific actions
    callMethod<TResponse>(methodName: string, ...args: unknown[]): Promise<TResponse>;
}

Using AppBridge Communication Methods

Initializing the AppBridge

To use the AppBridge in your React components, you'll need to initialize it and maintain its instance in your component's state. Typically, this is done within a useEffect hook:

import { createAppBridge, AppBridge } from '@jtl-software/cloud-apps-core';
import { useState, useEffect } from 'react';

function YourAppComponent() {
    // Store the AppBridge instance in component state
    const [appBridge, setAppBridge] = useState<AppBridge | undefined>(undefined);

    useEffect((): void => {
        console.log('[HelloWorldApp] createAppBridge...');
        createAppBridge().then(bridge => {
            console.log('[HelloWorldApp] bridge created!');
            // Store the bridge instance in state for use throughout your component
            setAppBridge(bridge);
        });
    }, []);

    // Rest of your component...
}

The initialization process:

  1. Import the necessary functions from @jtl-software/cloud-apps-core
  2. Create a state variable to hold the AppBridge instance
  3. Use createAppBridge() to establish the connection with the host
  4. Once the bridge is created, you can immediately start calling methods or pass it down to child components.
  5. Store the bridge instance in your component's state for later use

The empty dependency array [] ensures that the effect runs only once when the component mounts.

Subscribe to Host Events

The subscribe method allows your app to listen for specific events emitted by the host environment.

// Listen for inventory updates
appBridge.subscribe("inventory:updated", async (data) => {
  console.log("Inventory updated:", data);
  return { status: "processed" };
});

When the host system triggers an "inventory:updated" event, your callback function will execute with the provided data.

Publish Messages to the Host

The publish method sends data to the host environment under a specific topic.

// Notify the host about completed action
await appBridge.publish("order:verification:complete", {
  orderId: "ORD-12345",
  verifiedBy: "app-user"
});

This is useful for informing the host about state changes or actions completed within your app.

Expose Methods to the Host

The exposeMethod function makes your app's functions callable by the host environment.

// Make a function available to the host
appBridge.exposeMethod("calculateShippingCost", (weight, destination) => {
  const baseCost = 5.99;
  const zoneRate = destination === "international" ? 2.5 : 1;
  return baseCost + (0.1 * weight * zoneRate);
});

This allows the host environment to directly use functionality implemented in your app.

Check if Method is Exposed

The isMethodExposed method verifies if a specific function has already been exposed to the host.

// Check if a method is already exposed
if (!appBridge.isMethodExposed("calculateTax")) {
  appBridge.exposeMethod("calculateTax", (amount, rate) => {
    return amount * (rate / 100);
  });
}

This helps prevent errors from attempting to expose the same method multiple times.

Call Host Methods

The callMethod function allows your app to invoke functions provided by the host environment.

// Get user information
const userProfile = await appBridge.callMethod("getUserProfile");

// Call a method with parameters
const orderDetails = await appBridge.callMethod("getOrderDetails", "ORD-5678");

This enables your app to access host functionality, data, and services.

Communication Flow

The connection facilitates a two-way communication path: your app's appBridge instance talks to the corresponding hostAppBridge instance within the JTL cloud service.

App Frontend (in Iframe)appBridge (Instance)hostAppBridge (Instance)JTL Cloud Service (Setup/ERP)Later InteractionsInitialize (createAppBridge())Establish ConnectionConnection ReadyBridge Instance ReadycallMethod("methodName", args...)Invoke methodName(args...)Execute Host LogicReturn ResultForward ResultReturn ResultApp Frontend (in Iframe)appBridge (Instance)hostAppBridge (Instance)JTL Cloud Service (Setup/ERP)

Creating a AppBridge Instance

To establish communication with the host environment, you need to create a AppBridge instance:

import { createAppBridge, AppBridge } from '@jtl-software/cloud-apps-core';
  
const [appBridge, setAppBridge] = useState<AppBridge | undefined>(undefined);

useEffect((): void => {
  console.log('[HelloWorldApp] createAppBridge...');
  createAppBridge().then(bridge => {
    console.log('[HelloWorldApp] bridge created!');
    setAppBridge(bridge);
  });
}, []);

Environment-Specific Methods

The AppBridge exposes different methods depending on which environment your app is running in:

Setup Environment Methods

MethodParametersDescription
testargs: stringSimple test method that logs arguments to console
test2msg: string, age: numberTest method with multiple parameters
setupcompletedNoneUpdates the app's status to "active" in the hub
getSessionTokenNoneReturns the current session token

ERP Environment Methods

MethodParametersDescription
getCurrentTimeNoneReturns the current time as a Date object
getSessionTokenNoneReturns the current session token

Calling Methods

To call methods exposed by the host environment, use the callMethod function:

// Basic syntax
appBridge.callMethod("methodName", parameter1, parameter2, ...);

// Example: Getting a session token
const sessionToken = await appBridge.callMethod("getSessionToken");

Session Token Usage

For more detailed information about working with session tokens in your app, please refer to our Session Token documentation. This guide explains how to properly use the token for authentication, and token lifecycle management.