> 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 a Site Extension
## Article: Identify Instance CLI Widget
## Article Link: https://dev.wix.com/docs/wix-cli/guides/extensions/site-extensions/identify-the-app-instance-in-a-site-extension.md
## Article Content:
# Identify the App Instance in a Site Widget
**CLI Documentation Notice**
You're viewing documentation for the new Wix CLI, which we recommend for all new projects. [Determine which CLI your project uses](https://dev.wix.com/docs/wix-cli/guides/development/determine-which-cli-your-project-uses.md).
Previous CLI documentation:
- Wix CLI for Apps: [Identify the App Instance in a Site Widget Built with the CLI](https://dev.wix.com/docs/wix-cli/legacy-clis/legacy-wix-cli-for-apps/supported-extensions/site-extensions/custom-element-site-widgets/identify-the-app-instance-in-a-site-widget-built-with-the-cli.md).
For security reasons, [app instance ID](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/about-app-instances.md) (`instanceId`) isn't directly accessible in [site widgets](https://dev.wix.com/docs/wix-cli/guides/extensions/site-extensions/custom-elements/add-a-custom-element-extension.md) or settings panels. Instead, you can securely extract it by sending a Wix access token to an [HTTP endpoint](https://dev.wix.com/docs/wix-cli/guides/development/http-endpoints/about-http-endpoints.md). The endpoint can decode the token, get the instance ID or instance data, and perform any necessary business logic.
This article explains how to:
* **Backend:** Create an HTTP endpoint to identify the app instance.
* **Frontend:** Pass a Wix access token from your custom element to your HTTP endpoint.
## Step 1 | Create an HTTP endpoint
To securely identify the app instance:
1. Create an [HTTP endpoint](https://dev.wix.com/docs/wix-cli/guides/development/http-endpoints/add-http-endpoints-to-your-project.md) in your project's `src/pages/api/` directory.
1. In your HTTP endpoint file, import the `auth` submodule from the Essentials API:
```javascript
import { auth } from "@wix/essentials";
```
1. Depending on your [use case](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/about-app-instances.md#example-use-cases-1), you may only need `instanceId` or you may need more detailed app instance data.
* **To extract `instanceId`:**
In your Astro endpoint's `GET` function, call [`getTokenInfo()`](https://dev.wix.com/docs/sdk/core-modules/essentials/auth.md#gettokeninfo) to extract `instanceId` from the access token.
```javascript
const tokenInfo = await auth.getTokenInfo();
const instanceId = tokenInfo.instanceId;
```
* **To fetch instance data:**
Elevate API call permissions to an app identity. Then, call [`getAppInstance()`](https://dev.wix.com/docs/api-reference/app-management/app-instance/get-app-instance.md). Elevation is necessary because access tokens sent from site widgets are tied to a site visitor or member [identity](https://dev.wix.com/docs/build-apps/develop-your-app/access/about-identities.md), which don't have access to instance data.
```javascript
import { appInstances } from "@wix/app-management";
import { auth } from "@wix/essentials";
// Elevate permissions in your Astro endpoint's GET function
const elevatedGetAppInstance = auth.elevate(appInstances.getAppInstance);
const instanceResponse = await elevatedGetAppInstance();
```
## Step 2 | Pass a Wix access token to your Astro endpoint
To pass a Wix access token from your site widget to your Astro endpoint:
1. [Add a Site Widget Extension in the CLI](https://dev.wix.com/docs/wix-cli/guides/extensions/site-extensions/site-widgets/about-site-widget-extensions.md). If you already have a site widget, skip to the next step.
2. In your site widget component file, import the `httpClient` submodule from the [Essentials API](https://dev.wix.com/docs/sdk/core-modules/essentials/introduction.md).
**For Editor React Component site widgets** in `component.tsx`:
```javascript
import { httpClient } from '@wix/essentials';
```
**For Custom Element site widgets** in `element.tsx`:
```javascript
import { httpClient } from '@wix/essentials';
```
3. Call [`fetchWithAuth()`](https://dev.wix.com/docs/sdk/core-modules/essentials/http-client.md#fetchwithauth) to send a request to your Astro endpoint with a Wix access token.
```javascript
const response = await httpClient.fetchWithAuth(`${import.meta.env.BASE_API_URL}/api/`);
```
For Custom Element site widgets with settings panels, you can also call `fetchWithAuth()` from your `panel.tsx` file to get `instanceId` in the settings panel.
## Examples
Depending on your [use case](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/about-app-instances.md#example-use-cases-1), the logic of your Astro endpoint will vary. For example, you may only need to extract `instanceId` and then use it to make a request to your own database. Alternatively, you may wish to request app instance data from Wix, in which case you'd need to elevate your access token.
See the relevant example for your use case:
* [Astro Endpoint: Extract `instanceId`](#astro-endpoint-extract-instanceid)
* [Astro Endpoint: Fetch instance data](#astro-endpoint-fetch-instance-data)
* [Editor React Component: Call your Astro endpoint](#editor-react-component-call-your-astro-endpoint)
* [Custom Element: Call your Astro endpoint](#custom-element-call-your-astro-endpoint)
### Astro Endpoint: Extract `instanceId`
The following example is based on an Astro endpoint located at `src/pages/api/get-instance.ts`. The endpoint extracts `instanceId` from the access token provided by the frontend request.
```javascript
import { auth } from "@wix/essentials";
// Edit this code based on your business logic
const mockDatabaseQuery = async (instanceId) => {
console.log(`Mock database query with instance ID: ${instanceId}`);
if (instanceId) {
return {
status: "Success",
};
} else {
return {
status: "No instance ID.",
};
}
};
export async function GET({ request }) {
try {
// Extract the app instance ID from the access token
const tokenInfo = await auth.getTokenInfo();
const instanceId = tokenInfo.instanceId;
console.log("Instance ID:", instanceId);
// Edit this code based on your business logic
const data = await mockDatabaseQuery(instanceId);
return new Response(JSON.stringify(data), {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Error decoding token:", error);
return new Response(JSON.stringify({ error: "Failed to process request" }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
}
```
### Astro Endpoint: Fetch instance data
The following example is based on an Astro endpoint located at `src/pages/api/get-instance.ts`. The endpoint elevates permissions and requests instance data from Wix.
```javascript
import { auth } from "@wix/essentials";
import { appInstances } from "@wix/app-management";
export async function GET({ request }) {
try {
const elevatedGetAppInstance = auth.elevate(appInstances.getAppInstance);
const instanceResponse = await elevatedGetAppInstance();
return new Response(JSON.stringify(instanceResponse.data), {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("Error decoding token:", error);
return new Response(JSON.stringify({ error: "Failed to process request" }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
}
```
### Editor React Component: Call your Astro endpoint
The following example creates an Editor React Component site widget that makes a request to the `get-instance` Astro endpoint.
```typescript
import type { FC } from 'react';
import { useState, useEffect } from 'react';
import { httpClient } from '@wix/essentials';
interface Props {
id: string;
className: string;
}
const Component: FC = (props) => {
const [instanceData, setInstanceData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const callMyAstroEndpoint = async () => {
try {
// Send the access token to your Astro endpoint
const response = await httpClient.fetchWithAuth(
`${import.meta.env.BASE_API_URL}/api/get-instance`
);
const data = await response.json();
setInstanceData(data);
setLoading(false);
} catch (err) {
console.error("Error calling get-instance:", err);
setError("Failed to fetch instance data.");
setLoading(false);
}
};
callMyAstroEndpoint();
}, []);
return (
My Widget
{loading ? (
Loading instance data...
) : error ? (
{error}
) : (
Success! Instance data loaded.
)}
);
};
export default Component;
```
### Custom Element: Call your Astro endpoint
The following example creates a custom element that makes a request to the `get-instance` Astro endpoint.
```javascript
import React, { useState, useEffect } from 'react';
import reactToWebComponent from 'react-to-webcomponent';
import ReactDOM from 'react-dom';
import styles from './element.module.css';
import { httpClient } from '@wix/essentials';
interface Props {
displayName: string;
}
const CustomElement: React.FC = ({ displayName }) => {
const [instanceData, setInstanceData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const callMyAstroEndpoint = async () => {
try {
// Send the access token to your Astro endpoint
const response = await httpClient.fetchWithAuth(`${import.meta.env.BASE_API_URL}/api/get-instance`);
const data = await response.json();
setInstanceData(data);
setLoading(false);
} catch (err) {
console.error("Error calling get-instance:", err);
setError("Failed to fetch instance data.");
setLoading(false);
}
};
callMyAstroEndpoint();
}, []);
return (
Hello {displayName || 'Wix CLI'}
{loading ? (
Loading instance data...
) : error ? (
{error}
) : (
)}
);
};
const customElement = reactToWebComponent(
CustomElement,
React,
ReactDOM as any,
{
props: {
displayName: 'string',
},
}
);
export default customElement;
```
## See also
* [About Site Widget Extensions](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/site-widgets/about-site-widget-extensions.md)
* [About App Instances](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/about-app-instances.md)