---
title: "Trigger CC via a Webhook"
description: "Webhooks can be configured to trigger a CloudCode task automatically. When the webhook fires, the task is automatically enqueued and executed."
permalink: /docs/cloudcode/triggering-a-cloudcode-task/trigger-cc-via-a-webhook/
---
# Trigger CC via a Webhook

Webhooks can be configured to trigger a CloudCode task automatically. When the webhook fires, the task is automatically enqueued and executed.

To trigger a task called `my_job_card_ready` whenever a `job_card` is created on the backend, add the following webhook definition in the [model reference](/docs/build/data-model-configuration/model/):

**schema.xml**

```xml
<model name="job_card" label="Job Card">
    <!-- ... -->
    
    <webhook type="ready" receiver="cloudcode" action="my_job_card_ready" />
</model>
```

In the CloudCode Task:

<LanguageTabs defaultValue="JavaScript">
  <LanguageTab label="JavaScript">

```javascript
export async function run(params) {
  let object;
  if(this.source == CloudCode.WEBHOOK) {
    // Webhook
    object = params.object;
    // The object has the state of when the webhook was
    // triggered, which may be out of date. To work with the
    // current version, add:
    //   await object.reload();
  } else if(this.source == CloudCode.EDITOR_TEST && this.env == 'testing') {
    // Test - Create mock object
    object = DB.job_card.create();
  } else {
    throw new Error('Task must be run as a webhook');
  }
// Do something with the object here.
}
```

  </LanguageTab>
  <LanguageTab label="TypeScript">

```typescript
import { TaskContext } from '@journeyapps/cloudcode';

interface Params {
  object: any;
}

export async function run(this: TaskContext, params: Params) {
  let object;
  if(this.source == CloudCode.WEBHOOK) {
    // Webhook
    object = params.object;
    // The object has the state of when the webhook was
    // triggered, which may be out of date. To work with the
    // current version, add:
    //   await object.reload();
  } else if(this.source == CloudCode.EDITOR_TEST && this.env == 'testing') {
    // Test - Create mock object
    object = DB.job_card.create();
  } else {
    throw new Error('Task must be run as a webhook');
  }
// Do something with the object here.
}
```

  </LanguageTab>
</LanguageTabs>

Here's an example of a task that sends an email to a specified email address on a webhook:

<LanguageTabs defaultValue="JavaScript">
  <LanguageTab label="JavaScript">

```javascript
// Specify your details here
const SENDGRID_KEY = process.env.sendgrid_key; // Read the docs for env variables
const FROM_EMAIL = "you@example.com";

// Used for testing only
const TEST_EMAIL = "you@example.com";

async function email(params) {
  // Helper function to send an email via the sendgrid API.
  var response = await fetch('https://api.sendgrid.com/v3/mail/send', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + SENDGRID_KEY
    },
    accept: 'application/json',
    body: JSON.stringify(params)
  });
  if(response.ok) {
    return null;
  } else {
    throw new Error('Failed to send email: ' + response.statusText);
  }
}

export async function run(params) {
  let invoice;
  if(this.source == CloudCode.WEBHOOK) {
    invoice = params.object;
    // The invoice object has the state of when the webhook was
    // triggered, which may be out of date. To work with the
    // current version, add:
    //   await invoice.reload();
  } else if(this.source == CloudCode.EDITOR_TEST && this.env == 'testing') {
    // Test - Create mock object
    invoice = DB.invoice.create();
    invoice.client_name = 'Test Client';
    invoice.client_email = TEST_EMAIL;
  } else {
    throw new Error('Task must be run as a webhook');
  }

  console.log('Invoice', invoice);

  if(invoice.client_email == null) {
    return {error: 'no client email'};
  }

  console.log('Sending mail to', invoice.client_name, invoice.client_email);

  var body = `
Invoice for ${invoice.client_name}
----------------------------------------------

First Item    2 x R 12.00
Second Item   3 x R  6.00
----------------------------------------------
Total: R 42.00
`;

  await email({
    personalizations: [
      {
        to: [
          {
            email: invoice.client_email,
            name: invoice.client_name
          }
        ],
        subject: "Test Invoice: " + new Date().toISOString()
      }
    ],
    content: [
      {
        type: "text",
        value: body
      }
    ],
    from: {
      email: FROM_EMAIL,
      name: 'Invoice Mailer'
    }
  });
  console.log('Sent email.');

  return {success: true};
}
```

  </LanguageTab>
  <LanguageTab label="TypeScript">

```typescript
import { TaskContext } from '@journeyapps/cloudcode';

// Parameters supplied by the webhook trigger
interface Params {
  object: any;
}

// Specify your details here
const SENDGRID_KEY = process.env.sendgrid_key; // Read the docs for env variables
const FROM_EMAIL = "you@example.com";

// Used for testing only
const TEST_EMAIL = "you@example.com";

async function email(params: any) {
  // Helper function to send an email via the sendgrid API.
  var response = await fetch('https://api.sendgrid.com/v3/mail/send', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + SENDGRID_KEY
    },
    accept: 'application/json',
    body: JSON.stringify(params)
  });
  if(response.ok) {
    return null;
  } else {
    throw new Error('Failed to send email: ' + response.statusText);
  }
}

export async function run(this: TaskContext, params: Params) {
  let invoice;
  if(this.source == CloudCode.WEBHOOK) {
    invoice = params.object;
    // The invoice object has the state of when the webhook was
    // triggered, which may be out of date. To work with the
    // current version, add:
    //   await invoice.reload();
  } else if(this.source == CloudCode.EDITOR_TEST && this.env == 'testing') {
    // Test - Create mock object
    invoice = DB.invoice.create();
    invoice.client_name = 'Test Client';
    invoice.client_email = TEST_EMAIL;
  } else {
    throw new Error('Task must be run as a webhook');
  }

  console.log('Invoice', invoice);

  if(invoice.client_email == null) {
    return {error: 'no client email'};
  }

  console.log('Sending mail to', invoice.client_name, invoice.client_email);

  var body = `
Invoice for ${invoice.client_name}
----------------------------------------------

First Item    2 x R 12.00
Second Item   3 x R  6.00
----------------------------------------------
Total: R 42.00
`;

  await email({
    personalizations: [
      {
        to: [
          {
            email: invoice.client_email,
            name: invoice.client_name
          }
        ],
        subject: "Test Invoice: " + new Date().toISOString()
      }
    ],
    content: [
      {
        type: "text",
        value: body
      }
    ],
    from: {
      email: FROM_EMAIL,
      name: 'Invoice Mailer'
    }
  });
  console.log('Sent email.');

  return {success: true};
}
```

  </LanguageTab>
</LanguageTabs>

You can learn more about JourneyApps Webhooks in the documentation below:

- [webhooks external](/docs/app-features/webhooks-external/)
