> For the complete documentation index, see [llms.txt](https://docs.cuoral.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cuoral.com/integration/newsletter-subscription.md).

# Newsletter Subscription

Collect email subscribers directly from your website with beautiful, ready-to-use UI components or a simple programmatic API.

### Installation

The newsletter module is included in `inline.js`. No additional scripts needed — it's available automatically when you load the Cuoral widget:

```html
<script
  src="https://js.cuoral.com/inline.js"
  data-cuoral-key="your-public-key"
></script>
```

The `CuoralNewsletter` object is then globally available.

### Method 1: Modal Popup

Show a beautiful animated modal to collect subscriptions. Great for exit-intent, button clicks, or timed popups.

```javascript
CuoralNewsletter.showModal({
  title: "Stay in the loop",
  subtitle: "Get the latest updates delivered to your inbox.",
  buttonText: "Subscribe",
  color: "#6366f1",
  showName: true,
  showConsent: true,
  consentText: "I agree to receive emails and can unsubscribe anytime.",
  successTitle: "You're subscribed! 🎉",
  successMessage: "Check your inbox for confirmation.",
  tags: ["website-popup"],
  onSuccess: (data) => {
    console.log("Subscribed!", data);
  },
  onError: (error) => {
    console.error("Failed:", error);
  },
  onClose: () => {
    console.log("Modal closed");
  },
});
```

#### Modal Options

| Parameter        | Type      | Default                       | Description                      |
| ---------------- | --------- | ----------------------------- | -------------------------------- |
| `title`          | string    | `"Stay in the loop"`          | Modal heading                    |
| `subtitle`       | string    | `"Get the latest updates..."` | Description text                 |
| `buttonText`     | string    | `"Subscribe"`                 | Submit button label              |
| `color`          | string    | `"#6366f1"`                   | Brand/theme color (hex)          |
| `showName`       | boolean   | `false`                       | Show first & last name fields    |
| `showConsent`    | boolean   | `true`                        | Show consent checkbox            |
| `consentText`    | string    | `"I agree to receive..."`     | Custom consent label             |
| `successTitle`   | string    | `"You're subscribed! 🎉"`     | Title after success              |
| `successMessage` | string    | `"Thanks for subscribing..."` | Message after success            |
| `tags`           | string\[] | `[]`                          | Tags for subscriber segmentation |
| `onSuccess`      | function  | `null`                        | Callback with subscriber data    |
| `onError`        | function  | `null`                        | Callback with error details      |
| `onClose`        | function  | `null`                        | Callback when modal is closed    |

### Method 2: Inline Form Embed

Embed a form directly into any element on your page. Perfect for footers, sidebars, or dedicated signup sections.

```javascript
CuoralNewsletter.embed("#newsletter-container", {
  title: "Subscribe to our newsletter",
  subtitle: "Stay updated with the latest news.",
  layout: "inline",
  color: "#6366f1",
  buttonText: "Subscribe",
  showName: false,
  tags: ["footer-form"],
  onSuccess: (data) => console.log("Subscribed!", data),
  onError: (error) => console.error("Error:", error),
});
```

#### Embed Options

| Parameter          | Type              | Default                         | Description                      |
| ------------------ | ----------------- | ------------------------------- | -------------------------------- |
| `target` (1st arg) | string \| Element | —                               | CSS selector or DOM element      |
| `title`            | string            | `"Subscribe to our newsletter"` | Form heading                     |
| `subtitle`         | string            | `"Stay updated..."`             | Description text                 |
| `buttonText`       | string            | `"Subscribe"`                   | Submit button label              |
| `color`            | string            | `"#6366f1"`                     | Brand/theme color (hex)          |
| `showName`         | boolean           | `false`                         | Show first & last name fields    |
| `layout`           | string            | `"stacked"`                     | `"stacked"` or `"inline"`        |
| `tags`             | string\[]         | `[]`                            | Tags for subscriber segmentation |
| `onSuccess`        | function          | `null`                          | Callback with subscriber data    |
| `onError`          | function          | `null`                          | Callback with error details      |

#### Layout Options

* **`"inline"`** — Email input and button on the same row (compact, great for headers/footers)
* **`"stacked"`** — Fields stacked vertically (traditional form layout)

> **Note:** Inline layout only works when `showName` is `false`. If name fields are enabled, it falls back to stacked.

### Method 3: Programmatic Subscribe

For custom forms where you handle the UI yourself. Just pass the email and get the result.

```javascript
// Inside your own form submit handler
const result = await CuoralNewsletter.subscribe({
  email: "user@example.com",
  firstName: "John",        // optional
  lastName: "Doe",          // optional
  tags: ["custom-form"],    // optional
  customFields: {           // optional
    company: "Acme Inc",
    role: "Developer",
  },
});

if (result.status) {
  // Success!
  console.log(result.data);
  // { email: "user@example.com", contact_uid: "...", is_subscribed: true }
} else {
  // Error
  console.error(result.message);
}
```

#### Subscribe Options

| Parameter      | Type      | Required | Description                |
| -------------- | --------- | -------- | -------------------------- |
| `email`        | string    | ✅ Yes    | Subscriber's email address |
| `firstName`    | string    | No       | First name                 |
| `lastName`     | string    | No       | Last name                  |
| `tags`         | string\[] | No       | Tags for segmentation      |
| `customFields` | object    | No       | Custom key-value metadata  |

#### Response Format

```json
{
  "status": true,
  "message": "Successfully subscribed",
  "data": {
    "email": "user@example.com",
    "contact_uid": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "is_subscribed": true,
    "subscription_state": "active",
    "requires_confirmation": false
  }
}
```

### Examples

#### Trigger modal on button click

```html
<button onclick="CuoralNewsletter.showModal({ color: '#e11d48' })">
  Subscribe Now
</button>
```

#### Embed in footer

```html
<div id="footer-newsletter"></div>
<script>
  CuoralNewsletter.embed("#footer-newsletter", {
    layout: "inline",
    title: "",
    subtitle: "",
    buttonText: "→",
    color: "#1e293b",
  });
</script>
```

#### Exit-intent popup

```javascript
let shown = false;
document.addEventListener("mouseout", (e) => {
  if (e.clientY < 10 && !shown) {
    shown = true;
    CuoralNewsletter.showModal({
      title: "Wait! Don't leave yet 👋",
      subtitle: "Subscribe for a 10% discount on your first purchase.",
      color: "#059669",
      tags: ["exit-intent"],
    });
  }
});
```

#### Custom form integration

```html
<form id="my-form">
  <input type="email" id="my-email" placeholder="Enter email" />
  <button type="submit">Subscribe</button>
</form>

<script>
document.getElementById("my-form").addEventListener("submit", async (e) => {
  e.preventDefault();
  const email = document.getElementById("my-email").value;

  const result = await CuoralNewsletter.subscribe({ email });

  if (result.status) {
    alert("Subscribed successfully!");
  } else {
    alert("Error: " + result.message);
  }
});
</script>
```

### Notes

* **`org_identifier`** is automatically set from your `data-cuoral-key` attribute.
* **`source_details`** auto-captures the current page URL where the subscription happened.
* **`consent`** is auto-generated with a timestamp when the user subscribes.
* The modal auto-closes 4 seconds after successful subscription.
* All forms include built-in email validation.
* Responsive design works on all screen sizes.
* Demo URL: <https://js.cuoral.com/newsletter-demo.html>
