> 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 Backend Environments ## Article: Identify the App Instance in Backend Environments ## Article Link: https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-backend-environments.md ## Article Content: # Identify the App Instance in Backend 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 backend environments. ## CLI web method extension For [web methods](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/backend-extensions/apis/web-methods/about-web-method-extensions.md), you can: * Get `instanceId` by calling [`auth.getTokenInfo()`](https://dev.wix.com/docs/sdk/core-modules/essentials/auth.md). * Fetch instance data by passing [`getAppInstance`](https://dev.wix.com/docs/api-reference/app-management/app-instance/get-app-instance.md) to [`auth.elevate()`](https://dev.wix.com/docs/sdk/core-modules/essentials/auth.md) and calling the elevated function. The following example logs the `instanceId`, and then elevates the access token to make a request to [`getAppInstance()`](https://dev.wix.com/docs/api-reference/app-management/app-instance/get-app-instance.md). Elevation is necessary because web methods are called from frontend code, and frontend access tokens are associated with [site visitors or members](https://dev.wix.com/docs/build-apps/develop-your-app/access/about-identities.md), who lack permission to retrieve instance data. ```javascript import { webMethod, Permissions } from '@wix/web-methods'; import { auth } from '@wix/essentials'; import { appInstances } from "@wix/app-management"; export const getInstance = webMethod( Permissions.Anyone, async () => { const { instanceId } = await auth.getTokenInfo(); console.log(`App instance ID: ${instanceId}`); // (Optional) Fetch app instance data from Wix const elevatedGetAppInstance = auth.elevate(appInstances.getAppInstance); const { instance, site } = await elevatedGetAppInstance(); console.log("Response from Get App Instance:", { instance, site }); }, ); ``` ## CLI API extension For [CLI API extensions](https://dev.wix.com/docs/wix-cli/legacy-clis/legacy-wix-cli-for-apps/supported-extensions/backend-extensions/api/http-functions/add-http-function-extensions-with-the-cli.md), you can: * Get `instanceId` by calling [`auth.getTokenInfo()`](https://dev.wix.com/docs/sdk/core-modules/essentials/auth.md). * Fetch instance data by passing [`getAppInstance`](https://dev.wix.com/docs/api-reference/app-management/app-instance/get-app-instance.md) to [`auth.elevate()`](https://dev.wix.com/docs/sdk/core-modules/essentials/auth.md) and calling the elevated function.
**Important:** For this to work, you must send a Wix access token from the frontend to your API extension. This can be done with [`httpClient.fetchWithAuth()`](https://dev.wix.com/docs/sdk/core-modules/essentials/http-client.md), as explained in the [Wix-hosted frontend example](https://dev.wix.com/docs/build-apps/develop-your-app/access/app-instances/identify-the-app-instance-in-frontend-environments.md#wix-hosted-frontend).
The following example logs the `instanceId`, and then elevates the access token to make a request to [`getAppInstance()`](https://dev.wix.com/docs/api-reference/app-management/app-instance/get-app-instance.md). Elevation is necessary because web methods are called from frontend code, and frontend access tokens are associated with [site visitors or members](https://dev.wix.com/docs/build-apps/develop-your-app/access/about-identities.md), who lack permission to instance data. ```javascript import { webMethod, Permissions } from '@wix/web-methods'; import { auth } from '@wix/essentials'; import { appInstances } from '@wix/app-management'; export async function GET(req) { try { const { instanceId } = await auth.getTokenInfo(); console.log(`App instance ID: ${instanceId}`); // (Optional) Fetch app instance data from Wix const elevatedGetAppInstance = auth.elevate(appInstances.getAppInstance); const { instance, site } = await elevatedGetAppInstance(); console.log("Response from Get App Instance:", { instance, site }); } catch { return new Response({ error: "Failed to process request" }, { status: 500 }); } } ``` ## Blocks backend function For [Blocks backend functions](https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/wix-blocks/code-in-blocks/add-code-files-to-your-app.md#add-backend-files), you can: * Get `instanceId` by calling [`auth.getTokenInfo()`](https://dev.wix.com/docs/sdk/core-modules/essentials/auth.md). * Fetch instance data by passing [`getAppInstance`](https://dev.wix.com/docs/api-reference/app-management/app-instance/get-app-instance.md) to [`auth.elevate()`](https://dev.wix.com/docs/sdk/core-modules/essentials/auth.md) and calling the elevated function. Then, you can call your Blocks backend function from your Blocks frontend code. The following example logs the `instanceId`, and then elevates the access token to make a request to [`getAppInstance()`](https://dev.wix.com/docs/api-reference/app-management/app-instance/get-app-instance.md). Elevation is necessary because Blocks backend functions are called from frontend code, and frontend access tokens are associated with [site visitors or members](https://dev.wix.com/docs/build-apps/develop-your-app/access/about-identities.md), who lack permission to instance data. ```javascript // Backend: instance.jsw import { auth } from "@wix/essentials"; import { appInstances } from "@wix/app-management"; export async function getInstance() { try { const { instanceId } = await auth.getTokenInfo(); console.log(`App instance ID: ${instanceId}`); // (Optional) Fetch app instance data from Wix const elevatedGetAppInstance = auth.elevate(appInstances.getAppInstance); const response = await elevatedGetAppInstance(); console.log("Response from Get App Instance:", response); return response; } catch { return new Response({ error: "Failed to process request" }, { status: 500 }); } } ``` > **Note**: If you're not able to use [Essentials](https://dev.wix.com/docs/sdk/core-modules/essentials/introduction.md), you can extract the Wix access token from the `authorization` header and send it to [Get Token Info](https://dev.wix.com/docs/rest/app-management/oauth-2/token-info.md). ## Self-hosted backend using the JavaScript SDK For a self-hosted backend using the SDK, you can: * Get `instanceId` by passing a Wix access token to [Token Info](https://dev.wix.com/docs/sdk/core-modules/essentials/auth.md). * Fetch instance data by [elevating the access token](https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/self-hosting/elevate-sdk-call-permissions-with-self-hosting.md) and using it to call [`getAppInstance()`](https://dev.wix.com/docs/api-reference/app-management/app-instance/get-app-instance.md). The following example creates a Node.js Express API called `get-instance-data`. The API receives an access token from the frontend (which has a visitor or member identity), decodes the token and logs the `instanceId`, and then creates a client with elevated permissions to fetch the app instance data. ```javascript import express from "express"; import cors from "cors"; import { createClient, AppStrategy } from "@wix/sdk"; import { appInstances } from "@wix/app-management"; const app = express(); const port = 5000; app.use(cors()); app.get("/get-instance-data", async (req, res) => { try { const accessToken = req.headers["authorization"]; if (!accessToken) { throw new Error("Access token is required."); } const tokenData = await axios.post( "https://www.wixapis.com/oauth2/token-info", { token: accessToken, }, ); const instanceId = tokenData.data.instanceId; console.log(`App instance ID: ${instanceId}`); const elevatedClient = createClient({ auth: await AppStrategy({ appId: "", appSecret: "", accessToken: accessToken, }).elevated(), modules: { appInstances, }, }); const instanceResponse = await elevatedClient.appInstances.getAppInstance(); console.log("Response from Get App Instance:", instanceResponse.data); return res.json(instanceResponse.data); } catch (error) { console.error("Error processing request:", error.message); return res.status(500).json({ error: "Failed to process request" }); } }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); }); ``` ## Self-hosted backend using the REST API For a self-hosted backend using the REST API, you can: * Get `instanceId` by passing a Wix access token to [Token Info](https://dev.wix.com/docs/sdk/core-modules/essentials/auth.md). * Fetch instance data by [elevating the access token](https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/self-hosting/elevate-rest-api-call-permissions-for-self-hosting.md) and using it to call [Get App Instance](https://dev.wix.com/docs/rest/app-management/app-instance/get-app-instance.md). The following example creates a Node.js Express API called `get-instance-data`. The API receives an access token from the frontend (which has a visitor or member identity), decodes the token and logs the `instanceId`, and then uses the `instanceId` to create an access token with app permissions to fetch the instance data. ```javascript import express from "express"; import axios from "axios"; import cors from "cors"; const app = express(); const port = 5000; app.use(cors()); // Define a backend API app.get("/get-instance-data", async (req, res) => { try { // Get the Wix access token from the `authorization` header const accessToken = req.headers["authorization"]; if (!accessToken) { throw new Error("Access token is required."); } // Extract the app instance ID from the access token const tokenResponse = await axios.post( "https://www.wixapis.com/oauth2/token-info", { token: accessToken, }, ); const instanceId = tokenResponse.data.instanceId; console.log(`App instance ID: ${instanceId}`); // Create a new access token with an app identity const newTokenResponse = await axios.post( "https://www.wixapis.com/oauth2/token", { grant_type: "client_credentials", client_id: "", client_secret: "", instanceId: instanceId, }, ); const elevatedAccessToken = newTokenResponse.data.access_token; // Use the new token to get instance data const instanceResponse = await axios.get( "https://www.wixapis.com/apps/v1/instance", { headers: { Authorization: `Bearer ${elevatedAccessToken}`, }, }, ); console.log("Response from Get App Instance:", instanceResponse.data); return res.json(instanceResponse.data); } catch (error) { console.error("Error processing request:", error.message); return res.status(500).json({ error: "Failed to process request" }); } }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); }); ``` ## Service plugin extension For [service plugins](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/backend-extensions/service-plugins/about-service-plugin-extensions.md), get `instanceId` from the `metadata` of the service plugin call. The following example is based on the [additional fees service plugin](https://dev.wix.com/docs/api-reference/business-solutions/e-commerce/extensions/additional-fees/additional-fees-service-plugin/introduction.md). ```javascript import { additionalFees } from '@wix/ecom/service-plugins'; additionalFees.provideHandlers({ calculateAdditionalFees: async ({ request, metadata }) => { console.log(`App instance ID: ${metadata.instanceId}`); return { additionalFees: [], }; }, }); ``` ## CLI event extension For [CLI event extensions](https://dev.wix.com/docs/wix-cli/legacy-clis/legacy-wix-cli-for-apps/supported-extensions/backend-extensions/events/add-event-extensions-with-the-cli.md), get `instanceId` from the `metadata` of the event. The following example is based on [`onPostCreated()`](https://dev.wix.com/docs/api-reference/business-solutions/blog/posts-stats/post-created.md). ```javascript import { posts } from "@wix/blog"; import { auth } from '@wix/essentials'; import { appInstances } from "@wix/app-management"; posts.onPostCreated(async (event) => { console.log(`App instance ID: ${event.metadata.instanceId}`); // (Optional) Fetch app instance data from Wix const elevatedGetAppInstance = auth.elevate(appInstances.getAppInstance); const { instance, site } = await elevatedGetAppInstance(); console.log("Response from Get App Instance:", { instance, site }); }); ```