Source: https://datafa.st/docs/api-create-goal
Markdown source: https://datafa.st/docs/api-create-goal.md
Description: API endpoint to programmatically create a custom goal event for a visitor.

# Create a custom goal

`POST https://datafa.st/api/v1/goals`

Create a custom goal for a specific visitor. Requires [Bearer Token](/docs/api-introduction) authentication.

## Request body

Send a JSON object with the following fields:

- `datafast_visitor_id` (String, required): The DataFast unique ID of the visitor. It is stored in the visitor's browser cookies, making it accessible in your backend API endpoints.
- `name` (String, required): Name for the goal (lowercase letters, numbers, underscores, hyphens, colons, max 64 chars).
- `metadata` (Object, optional): Custom parameters to enrich your event data.

### Custom parameters rules (in metadata object):
- **Property names:** lowercase letters, numbers, underscores (_), and hyphens (-) only. Max 64 characters.
- **Property values:** any string, max 255 characters. HTML and script content is automatically removed for security.
- **Limits:** maximum 10 custom parameters per event.

> A visitor needs to have at least one pageview before the goal can be created.

## Response

- **Success (200 OK):** Returns a confirmation message and the ID of the created event.
- **Errors:** See [API Introduction](/docs/api-introduction). A 400 occurs if the visitor is a bot. A 404 occurs if the visitor has no prior pageviews.

## Code examples

### Example request (Node.js/Express)

```javascript
// Your backend API endpoint
const handler = async (req, res) => {
  const datafast_visitor_id = req.cookies.datafast_visitor_id;

  try {
    const response = await fetch("https://datafa.st/api/v1/goals", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${DATAFAST_API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        datafast_visitor_id: datafast_visitor_id,
        name: "newsletter_signup",
        metadata: {
          name: "Elon Musk",
          email: "musk@x.com",
        }
      }),
    });

    const result = await response.json();
    console.log("Goal sent to DataFast:", result);

    res.status(200).send("Goal tracked");
  } catch (error) {
    console.error("Error sending goal to DataFast:", error);
    res.status(500).send("Failed to track goal");
  }
};    

```

### Success response (200 OK)

```json
{
  "status": "success",
  "data": [{
    "message": "Custom event created successfully",
    "eventId": "67f8b9b5c320277df9a9d681"
  }]
}
```
