> 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`).
> - If a reference page seems to be missing its schema (parameters, return types, or type definitions), append `?schema=true` to its `.md` URL (e.g. `https://dev.wix.com/docs/contexts/contexts/stores/category-info/use-category-info-context.md?schema=true`).
> - 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: Run an Automation from Site Code in Studio Two

## Article: Run an Automation from Site Code in Studio Two

## Article Link: https://dev.wix.com/docs/studio-two/code-your-site/build-a-custom-backend/automations/run-an-automation-from-site-code-in-studio-two.md

## Article Content:

# Run an Automation from Site Code in Studio Two

Run an [automation](https://dev.wix.com/docs/studio-two/code-your-site/build-a-custom-backend/automations/about-automations.md) when your site's code detects an event, such as a site visitor clicking a button in an [Editor React Component (ERC)](https://dev.wix.com/docs/studio-two/code-your-site/code-model/editor-react-components/about-editor-react-components.md). Your frontend code calls an [HTTP endpoint](https://dev.wix.com/docs/studio-two/code-your-site/build-a-custom-backend/http-endpoints/about-http-endpoints.md) in your site project, and the endpoint runs the automation through its custom trigger. The automation's actions then do the work, such as creating a task.

Follow the instructions below to:

1. Create an automation with a custom trigger.
2. Install the automations package.
3. Add an HTTP endpoint that runs the automation.
4. Call the endpoint from your frontend code.
5. Publish your site and check the automation.

## Step 1 | Create the automation

Create the automation in the site dashboard and copy its trigger ID, which your code uses to run it.

To create the automation:

1. In the site dashboard, go to **Automations**.
2. Click **Create Automation**, then **Start from Scratch**.
3. Click **Select a trigger**, and choose **Velo code trigger**.
4. Under **triggerID**, click **Copy**, and save the ID for Step 3.

   Don't use the code sample that the trigger panel shows. It's for sites that use web methods, which Studio Two doesn't have.
5. Define the payload structure, so the actions can use the message that your code sends. The field names must match the payload's keys:
   1. Click **Set Payload Data Structure**.
   2. Replace the sample JSON with the fields your code sends, using sample values. For example:

      ```json
      {
        "message": "Please call me back"
      }
      ```

   3. Click **Preview Structure**, check the fields, and click **Save Structure**.
6. Click **Apply**.
7. Add the actions you want the automation to run. Under the trigger, click **+**, then **Action**, and choose an action, such as **Create a task**.

   To use a payload field in an action, click **Customize** next to the action's field, click in the field, and choose the payload field under **Velo code trigger** in the list that opens.
8. Click **Activate**.

## Step 2 | Install the automations package

The endpoint calls [Run Trigger](https://dev.wix.com/docs/api-reference/business-management/automations/triggers/custom-trigger/run-trigger?apiView=SDK.md) from `@wix/automations`. If your project doesn't include that package, [install it](https://dev.wix.com/docs/studio-two/code-your-site/developer-environment/packages/work-with-npm-packages.md). In the **Code** tab terminal, run `npm install @wix/automations`.

## Step 3 | Add an HTTP endpoint that runs the automation

The endpoint receives the request from your frontend code, checks it, and runs the automation. Your endpoint needs to:

- Check the request body and reject an invalid request with a `400` response.
- Build the payload from the checked fields only, so the automation never receives a field that the caller added.
- Wrap `customTrigger.runTrigger()` with [`auth.elevate()`](https://dev.wix.com/docs/sdk/core-modules/essentials/auth.md#elevate), so the call runs with elevated permissions whoever calls the endpoint.

<blockquote class="caution">

__Caution:__
Any site visitor can call an HTTP endpoint, and every request that passes your checks runs the automation. A caller can run its actions, such as sending an email, as often as they like. If only some callers should run the automation, such as logged-in site members, check the caller first. See [Check the caller](https://dev.wix.com/docs/studio-two/code-your-site/build-a-custom-backend/http-endpoints/build-an-http-endpoint-in-studio-two.md#step-4--check-the-caller).

</blockquote>

To add the endpoint:

1. Add an HTTP endpoint extension, as in Step 1 of [Add an HTTP Endpoint Extension in Studio Two](https://dev.wix.com/docs/studio-two/code-your-site/build-a-custom-backend/http-endpoints/add-an-http-endpoint-extension-in-studio-two.md#step-1--add-an-http-endpoint). The rest of this article uses `request-callback` as the endpoint's **Name**.
2. Replace the contents of `src/api/request-callback.ts` with the following code, which sends a message from the request body to the automation. Replace `<your-trigger-id>`, including the angle brackets, with the ID you copied in Step 1.

   ```ts
   import type { APIRoute } from '@wix/custom-extensions/types';
   import { auth } from '@wix/essentials';
   import { customTrigger } from '@wix/automations';

   const TRIGGER_ID = '<your-trigger-id>';

   export const POST: APIRoute = async ({ request }) => {
     let body;
     try {
       body = await request.json();
     } catch {
       return Response.json({ error: 'Invalid request' }, { status: 400 });
     }

     const message = body?.message;
     if (typeof message !== 'string' || message.length === 0) {
       return Response.json({ error: 'Invalid request' }, { status: 400 });
     }

     const elevatedRunTrigger = auth.elevate(customTrigger.runTrigger);
     await elevatedRunTrigger({ triggerId: TRIGGER_ID, payload: { message } });

     return Response.json({ ok: true });
   };
   ```

3. Save the file.

## Step 4 | Call the endpoint from your frontend code

Call the endpoint from frontend code, such as an ERC event handler or a function that a [Data Source](https://dev.wix.com/docs/studio-two/code-your-site/code-model/data-sources/about-data-sources.md) exposes. Use `httpClient.fetchWithAuth()` from `@wix/essentials`, and build the full endpoint URL, because Wix serves endpoints from a different domain than your site's pages.

For example, add this function to a frontend code file outside `src/api/`, such as `src/lib/request-callback.ts`, and call it where you need it:

```ts
import { httpClient } from '@wix/essentials';

export async function requestCallback(message: string) {
  const origin = new URL(import.meta.url).origin;
  const basePath = import.meta.env.WIX_SERVER_BASE_PATH || '/';

  const response = await httpClient.fetchWithAuth(`${origin}${basePath}request-callback`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ message }),
  });

  if (!response.ok) {
    throw new Error(`The automation didn't run. Status: ${response.status}`);
  }
}
```

For how the URL is built and how to handle the response, see [Call the endpoint from your frontend code](https://dev.wix.com/docs/studio-two/code-your-site/build-a-custom-backend/http-endpoints/build-an-http-endpoint-in-studio-two.md#step-6--call-the-endpoint-from-your-frontend-code).

## Step 5 | Publish your site and check the automation

To check that the automation runs:

1. Publish your site.
2. On the live site, do whatever triggers your frontend code, such as clicking the button.
3. Check that the result of the automation's actions appears, such as the created task.

If the automation doesn't run, check the response status:

- `400`: The request body has no valid `message`.
- `404`: The URL is wrong. Build the full URL as in Step 4.
- `500`: The endpoint threw an error. Find the details on the [**Logs** page](https://dev.wix.com/docs/studio-two/test-your-site/work-with-logs/view-logs.md) in the site dashboard. A `Not Found` error means the trigger ID doesn't match an automation.
- `200`, but nothing happened: Check that the automation is active on the **Automations** page.

## See also

- [About Automations](https://dev.wix.com/docs/studio-two/code-your-site/build-a-custom-backend/automations/about-automations.md)
- [Build an HTTP Endpoint in Studio Two](https://dev.wix.com/docs/studio-two/code-your-site/build-a-custom-backend/http-endpoints/build-an-http-endpoint-in-studio-two.md)
- [Run Trigger](https://dev.wix.com/docs/api-reference/business-management/automations/triggers/custom-trigger/run-trigger?apiView=SDK.md)