# AppBridge Communication The `AppBridge` is a crucial component provided by the [`@jtl-software/cloud-apps-core`](https://www.npmjs.com/package/@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. ## 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. The example below shows initialization at the application root level: ```jsx import { createAppBridge } from '@jtl-software/cloud-apps-core'; createAppBridge().then(appBridge => { createRoot(document.getElementById('root')!).render( , ); }); ``` The initialization process: 1. Import the necessary functions from `@jtl-software/cloud-apps-core` 2. Use `createAppBridge()` to establish the connection with the host 3. Once the bridge is created, pass it as a prop to your main App component 4. The App component can then use the bridge instance directly or pass it down to child components 5. This approach ensures the bridge is available immediately when your app renders ### Subscribe to Host Events The `subscribe` method allows your app to listen for specific events emitted by the host environment. ```javascript // Listen for inventory updates appBridge.event.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. ```javascript // Notify the host about completed action await appBridge.event.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 `expose` function makes your app's functions callable by the host environment. ```javascript // Make a function available to the host appBridge.method.expose("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 `isExposed` method verifies if a specific function has already been exposed to the host. ```javascript // Check if a method is already exposed if (!appBridge.method.isExposed("calculateTax")) { appBridge.method.expose("calculateTax", (amount, rate) => { return amount * (rate / 100); }); } ``` This helps prevent errors from attempting to expose the same method multiple times. ### Call Host Methods The `call` function allows your app to invoke functions provided by the host environment. ```javascript // Get user information const userProfile = await appBridge.method.call("getUserProfile"); // Call a method with parameters const orderDetails = await appBridge.method.call("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. ```mermaid sequenceDiagram participant AppFrontend as App Frontend (in Iframe) participant AppBridge as appBridge (Instance) participant HostAppBridge as hostAppBridge (Instance) participant CloudService as JTL Cloud Service (Setup/ERP) AppFrontend->>AppBridge: Initialize (createAppBridge()) activate AppBridge AppBridge->>HostAppBridge: Establish Connection activate HostAppBridge HostAppBridge-->>AppBridge: Connection Ready deactivate HostAppBridge AppBridge-->>AppFrontend: Bridge Instance Ready deactivate AppBridge Note over AppFrontend, CloudService: Later Interactions AppFrontend->>AppBridge: method.call("methodName", args...) activate AppBridge AppBridge->>HostAppBridge: Invoke methodName(args...) activate HostAppBridge HostAppBridge->>CloudService: Execute Host Logic activate CloudService CloudService-->>HostAppBridge: Return Result deactivate CloudService HostAppBridge-->>AppBridge: Forward Result deactivate HostAppBridge AppBridge-->>AppFrontend: Return Result deactivate AppBridge ``` ## Creating a AppBridge Instance To establish communication with the host environment, you need to create a AppBridge instance: ```typescript import { createAppBridge } from '@jtl-software/cloud-apps-core'; createAppBridge().then(appBridge => { createRoot(document.getElementById('root')!).render( , ); }); ``` ## Environment-Specific Methods The AppBridge exposes different methods depending on which environment your app is running in: ### Setup Environment Methods | Method | Parameters | Description | | --- | --- | --- | | `test` | `args: string` | Simple test method that logs arguments to console | | `test2` | `msg: string, age: number` | Test method with multiple parameters | | `setupCompleted` | None | Updates the app's status to "active" in the hub | | `getSessionToken` | None | Returns the current session token | ### ERP Environment Methods | Method | Parameters | Description | | --- | --- | --- | | `getCurrentTime` | None | Returns the current time as a Date object | | `getSessionToken` | None | Returns the current session token | ## Calling Methods To call methods exposed by the host environment, use the `call` function: ```javascript // Basic syntax appBridge.method.call("methodName", parameter1, parameter2, ...); // Example: Getting a session token const sessionToken = await appBridge.method.call("getSessionToken"); ``` ## Session Token Usage For more detailed information about working with session tokens in your app, please refer to our [Session Token documentation](/products/appregistration/sessiontoken). This guide explains how to properly use the token for authentication, and token lifecycle management.