> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

## Resource: Identify the App Instance in Frontend Environments

## Article: Identify the App Instance in Frontend Environments

## Article Link: https://dev.wix.com/docs/build-apps/develop-your-app/auth/app-instances/identify-the-app-instance-in-frontend-environments.md

## Article Content:

# Identify the App Instance in Frontend Environments

When your app is installed on multiple Wix sites, you need a way to determine which site is making a request. This is done using the [app instance](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/about-app-instances.md).

In some cases, you may only need the `instanceId` to query your database and perform business logic. In other cases, you may want to fetch additional data about the app instance from Wix. This article covers both approaches across different frontend environments.

To identify the app instance in frontend environments:

1. Send a Wix access token to a secure backend API.
1. Decode the token in the backend to retrieve the `instanceId` and apply the necessary business logic.

> **Note**: The method for sending the access token depends on whether your frontend is [Wix-managed or self-managed](https://dev.wix.com/docs/sdk/articles/get-started/about-self-hosted-apps.md), as Wix-managed extensions automatically handle authentication.

This article focuses on how to send an access token to your backend. To learn how to decode it, see [Identify the App Instance in Backend Environments](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md).

<blockquote class="warning">

**Warning:** Don't trust an `instanceId` sent to your backend as plain text, as it can be manipulated by an attacker.

</blockquote>

## Wix-managed frontend

Wix-managed frontend extensions include those built with the [CLI](#cli) or [Blocks](#blocks).

### CLI

Frontend extensions built with the CLI can identify the app instance using a [CLI web method extension](https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-cli/supported-extensions/backend-extensions/web-methods/add-web-method-extensions-with-the-cli.md) or [CLI API extension](https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-cli/supported-extensions/backend-extensions/api/add-api-extensions-with-the-cli.md). Learn more [about differences between web methods and API extensions](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/backend-extensions/web-methods/about-web-method-extensions.md#web-methods-vs-api-extensions).

#### Web method

To identify the app instance using a web method:

1. Implement a [web method](https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-cli/supported-extensions/backend-extensions/web-methods/add-web-method-extensions-with-the-cli.md)  to decode a Wix access token, based on the [web method backend example](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md#cli-web-method-extension).
1. Import the web method in your frontend code. For example:

    ```javascript
    import { getInstance } from "src/backend/get-instance.web.ts";
    ```

1. Call the web method. For example:

    ```javascript
    getInstance().then((result) => console.log(result));
    ```

#### API extension

To identify the app instance using an API extension:

1. Implement an [API extension](https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-cli/supported-extensions/backend-extensions/api/add-api-extensions-with-the-cli.md) to decode a Wix access token, based on the [API extension backend example](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md#cli-api-extension).
1. Install [Essentials](https://dev.wix.com/docs/sdk/core-modules/essentials/introduction.md).
1. Import [`httpClient`](https://dev.wix.com/docs/sdk/core-modules/essentials/http-client.md).

    ```javascript
    import { httpClient } from "@wix/essentials";
    ```

1. Call your API from your frontend code using `fetchWithAuth()`.

    ```javascript
    const response = await httpClient.fetchWithAuth(
      `${import.meta.env.BASE_API_URL}/<YOUR_BACKEND_API_NAME>`,
    );
    ```

### Blocks

Frontend extensions built with Blocks can identify the app instance using a Blocks backend function or a self-managed backend.

#### Blocks backend function

To identify the app instance using a Blocks backend function:

1. Create a [backend code file](https://dev.wix.com/docs/build-apps/develop-your-app/develop-an-app-with-blocks/code-in-blocks/about-coding-in-blocks.md#code-files-and-folders).
1. Implement a function in your backend file to decode a Wix access token, based on the [Blocks backend example](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md#blocks-backend-function).
1. Call your backend from your widget code. For example:

  ```javascript
  // The import varies based on the name of your file and function.
  import { getInstance } from 'backend/instance';

  $w.onReady(function () {
    getInstance().then(response => {
      console.log("Response from my Get Instance function", response);
    })
    .catch(error => {
      console.log(error);
    });
  });
  ```

Alternatively, you can use the [`getDecodedAppInstance()`](https://dev.wix.com/docs/velo/apis/wix-application/get-decoded-app-instance.md) Velo API.

#### Self-managed backend

To identify the app instance using a self-managed backend:

1. Implement a backend API to decode an access token and identify the app instance, based on one of the following examples:
   * [Self-managed backend using the REST API](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md#self-hosted-backend-using-the-rest-api)
   * [Self-managed backend using the JavaScript SDK](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md#self-hosted-backend-using-the-javascript-sdk)
1. Install [Essentials](https://dev.wix.com/docs/sdk/core-modules/essentials/introduction.md).
1. Import [`httpClient`](https://dev.wix.com/docs/sdk/core-modules/essentials/http-client.md).

    ```javascript
    import { httpClient } from "@wix/essentials";
    ```

1. In your Blocks frontend code, send a Wix access token to your backend by calling `fetchWithAuth()`.

    ```javascript
    const response = await httpClient.fetchWithAuth(`<YOUR_BACKEND_API>`);
    ```

## Self-managed frontend

For self-managed site extensions, the method of sending an access token to your backend varies depending on the technology:

* [Custom element](#custom-element)
* [Embedded script](#embedded-script)
* [iframe](#iframe)

<blockquote class="important">

**Important:** The backend is responsible for decoding the token and identifying the app instance. For more information, see [Identify the App Instance in Backend Environments](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md).

</blockquote>

#### Custom element

To identify the app instance from a self-managed custom element:

1. Implement a backend API to decode an access token and identify the app instance, based on one of the following examples:
   * [Self-managed backend using the REST API](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md#self-hosted-backend-using-the-rest-api)
   * [Self-managed backend using the JavaScript SDK](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md#self-hosted-backend-using-the-javascript-sdk)
1. In your frontend:
   1. Create a [Wix client](https://dev.wix.com/docs/sdk/core-modules/sdk/wix-client.md) with [`site`](https://dev.wix.com/docs/sdk/host-modules/site/introduction.md) host and authentication.
   1. Inject the custom element with a Wix access token.
   1. Send a Wix access token to your backend by calling [`fetchWithAuth()`](https://dev.wix.com/docs/sdk/core-modules/sdk/wix-client.md).

The following example demonstrates only the frontend logic.

```javascript
import { site } from "@wix/site";
import { createClient } from "@wix/sdk";

// Create a Wix client with site authentication and site host
const myWixClient = createClient({
  auth: site.auth(),
  host: site.host({ applicationId: "<YOUR_APP_ID>" }),
});

class MyCustomElement extends HTMLElement {
  constructor() {
    super();
    // Inject the Wix access token to your custom element
    this.accessTokenListener = myWixClient.auth.getAccessTokenInjector();
  }

  connectedCallback() {
    this.innerHTML = "<p>My custom element loaded successfully!</p>";
    this.callMyBackend();
  }

  async callMyBackend() {
    try {
      // Send a Wix access token to your backend
      const response = await myWixClient.fetchWithAuth("<YOUR_BACKEND_API_URL>");
      const data = await response.json();
      console.log("Response from get-instance:", data);
    } catch (error) {
      console.error("Error calling get-instance:", error);
    }
  }
}

customElements.define("<YOUR_CUSTOM_ELEMENT_TAG_NAME>", MyCustomElement);
```

#### Embedded script

To identify the app instance from a self-managed embedded script:

1. Implement a backend API to decode an access token and identify the app instance, based on one of the following examples:
   * [Self-managed backend using the REST API](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md#self-hosted-backend-using-the-rest-api)
   * [Self-managed backend using the JavaScript SDK](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md#self-hosted-backend-using-the-javascript-sdk)
1. In your frontend:
   1. Create a [Wix client](https://dev.wix.com/docs/sdk/core-modules/sdk/wix-client.md) with [`site`](https://dev.wix.com/docs/sdk/host-modules/site/introduction.md) host and authentication.
   1. Inject the embedded script with a Wix access token.
   1. Send a Wix access token to your backend by calling [`fetchWithAuth()`](https://dev.wix.com/docs/sdk/core-modules/sdk/wix-client.md).

The following examples demonstrate only the frontend logic.

**ECMAScript Module**

```html
<script accesstoken="true" type="module">
  import { site } from "@wix/site";
  import { createClient } from "@wix/sdk";
  import { seo } from "@wix/site-seo";

  // Create a Wix client with site authentication and site host
  const myWixClient = createClient({
    auth: site.auth(),
    host: site.host({ applicationId: "<YOUR_APP_ID>" }),
  });

  // Inject the Wix access token to your embedded script
  export const injectAccessTokenFunction = myWixClient.auth.getAccessTokenInjector();

  const callMyBackend = async () => {
    // Send a Wix access token to your backend
    const response = await myWixClient.fetchWithAuth("<YOUR_BACKEND_API_URL>");
    console.log("Response from my backend:", response.data);
  };

  callMyBackend();
</script>
```

**Standard**

```javascript
<script type="text/javascript" src="./my-file.js"></script>

// my-file.js
import { site } from "@wix/site";
import { createClient } from "@wix/sdk";
import { seo } from "@wix/site-seo";

// Create a Wix client with site authentication and site host
const myWixClient = createClient({
  auth: site.auth(),
  host: site.host({ applicationId: "<YOUR_APP_ID>" }),
});

const callMyBackend = async () => {
  // Send a Wix access token to your backend
  const response = await myWixClient.fetchWithAuth("<YOUR_BACKEND_API_URL>");
  console.log("Response from my backend:", response.data);
};

callMyBackend();
```

#### iframe

Wix provides iframes with an encoded `instance` query parameter. This is relevant for self-managed dashboard pages, dashboard plugins, settings panels, and external links.

To identify the app instance from an iframe:

1. Retrieve the `instance` query parameter from the URL.
1. Pass the `instance` value as the `token` to [Token Info](https://dev.wix.com/docs/rest/app-management/oauth-2/token-info.md).
1. (Optional) Use the returned `instanceId` to create an app access token and call [Get App Instance](https://dev.wix.com/docs/rest/app-management/app-instance/get-app-instance.md).

```javascript
const express = require("express");
const axios = require("axios");

const app = express();

app.get("/dashboard", async (req, res) => {
  const instance = req.query.instance;
  if (!instance) return res.status(400).send("Missing instance parameter");

  try {
    // Fetch token info from Wix API
    const tokenResponse = await axios.post("https://www.wixapis.com/oauth2/token-info", {
      token: instance,
    });

    const instanceId = tokenResponse.data.instanceId;
    console.log(`App instance ID: ${instanceId}`);

    // (Optional) Fetch additional app instance data from Wix
    const createTokenResponse = await axios.post("https://www.wixapis.com/oauth2/token", {
      grant_type: "client_credentials",
      client_id: "<YOUR_APP_ID>",
      client_secret: "<YOUR_APP_SECRET>",
      instanceId: instanceId,
    });

    const accessToken = createTokenResponse.data.access_token;
    const instanceResponse = await axios.get("https://www.wixapis.com/apps/v1/instance", {
      headers: { Authorization: `Bearer ${accessToken}` },
    });

    console.log("Response from Get App Instance:", instanceResponse.data);

    res.send(`
      <html>
        <head>
          <title>Dashboard</title>
        </head>
        <body>
          <h1>My Test Dashboard</h1>
          <p>Successfully retrieved app instance data.</p>
        </body>
      </html>
    `);

  } catch (err) {
    console.error("Error:", err);
    res.status(500).send("Failed to verify instance");
  }
});

app.listen(3000, () => console.log("Server running on port 3000"));
```

> **Note**: If your iframe content runs client-side JavaScript and needs to communicate with your server, create a [Wix Client](https://dev.wix.com/docs/sdk/core-modules/sdk/wix-client.md) and call `fetchWithAuth()` to include a Wix access token in the request.