Skip to content

loops-so/loops-js

Loops JavaScript/TypeScript SDK

Introduction

This is the official JavaScript SDK for Loops, with full TypeScript support.

It lets you easily integrate with the Loops API in any JavaScript project.

Installation

You can install the package from npm:

npm install loops

Minimum Node version required: 18.0.0.

You will need a Loops API key to use the package.

In your Loops account, go to the API Settings page and click "Generate key".

Copy this key and save it in your application code (for example as LOOPS_API_KEY in an .env file).

See the API documentation to learn more about rate limiting and error handling.

Usage

import { LoopsClient, APIError } from "loops";

const loops = new LoopsClient(process.env.LOOPS_API_KEY);

try {
  const resp = await loops.createContact("email@provider.com");
  // resp.success and resp.id available when successful
} catch (error) {
  if (error instanceof APIError) {
    // JSON returned by the API is in error.json and the HTTP code is in error.statusCode
    // error.json may be null if the response was not valid JSON (e.g., from a load balancer)
    // In that case, the raw response text is available in error.rawBody
    console.log(error.json);
    console.log(error.statusCode);
    console.log(error.rawBody);
  } else {
    // Non-API errors
  }
}

Handling rate limits

If you import RateLimitExceededError you can check for rate limit issues with your requests.

You can access details about the rate limits from the limit and remaining attributes.

import { LoopsClient, APIError, RateLimitExceededError } from "loops";

const loops = new LoopsClient(process.env.LOOPS_API_KEY);

try {
  const resp = await loops.createContact("email@provider.com");
} catch (error) {
  if (error instanceof RateLimitExceededError) {
    console.log(`Rate limit exceeded (${error.limit} per second)`);
    // Code here to re-try this request
  } else {
    // Handle other errors
  }
}

Default contact properties

Each contact in Loops has a set of default properties. These will always be returned in API results.

  • id
  • email
  • firstName
  • lastName
  • source
  • subscribed
  • userGroup
  • userId
  • optInStatus

Custom contact properties

You can use custom contact properties in API calls. Please make sure to add custom properties in your Loops account before using them with the SDK.

Methods


testApiKey()

Test that an API key is valid.

API Reference

Parameters

None

Example

const resp = await loops.testApiKey();

Response

{
  "success": true,
  "teamName": "My team"
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 401 Unauthorized
{
  "error": "Invalid API key"
}

createContact()

Create a new contact.

API Reference

Parameters

Name Type Required Notes
email string Yes If a contact already exists with this email address, an error response will be returned.
properties object No An object containing default and any custom properties for your contact.
Please add custom properties in your Loops account before using them with the SDK.
Values can be of type string, number, null (to reset a value), boolean or date (see allowed date formats).
mailingLists object No An object of mailing list IDs and boolean subscription statuses.

Examples

const resp = await loops.createContact({ email: "hello@gmail.com" });

const contactProperties = {
  firstName: "Bob" /* Default property */,
  favoriteColor: "Red" /* Custom property */,
};
const mailingLists = {
  cm06f5v0e45nf0ml5754o9cix: true /* Subscribe */,
  cm16k73gq014h0mmj5b6jdi9r: false /* Unsubscribe */,
};
const resp = await loops.createContact({
  email: "hello@gmail.com",
  properties: contactProperties,
  mailingLists,
});

Response

{
  "success": true,
  "id": "clw9h3y5a014yl70k9m2n4p8q"
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 400 Bad Request
{
  "success": false,
  "message": "An error message here."
}

updateContact()

Update a contact. This method will create a contact if one doesn't already exist.

Note: To update a contact's email address, the contact requires a userId value. Then you can make a request with their userId and an updated email address.

API Reference

Parameters

Name Type Required Notes
email string No The email address of the contact to update. If there is no contact with this email address, a new contact will be created using the email and properties in this request. Required if userId is not present.
userId string No The contact's unique user ID. If you use userId without email, this value must have already been added to your contact in Loops. Required if email is not present.
properties object No An object containing default and any custom properties for your contact.
Please add custom properties in your Loops account before using them with the SDK.
Values can be of type string, number, null (to reset a value), boolean or date (see allowed date formats).
mailingLists object No An object of mailing list IDs and boolean subscription statuses.

Example

const resp = await loops.updateContact({
  email: "hello@gmail.com",
  properties: {
    firstName: "Bob" /* Default property */,
    favoriteColor: "Blue" /* Custom property */,
  },
});

/* Updating a contact's email address using userId */
const resp = await loops.updateContact({
  userId: "1234",
  email: "newemail@gmail.com",
});

/* Subscribe a contact to a mailing list */
const resp = await loops.updateContact({
  email: "hello@gmail.com",
  mailingLists: {
    cm06f5v0e45nf0ml5754o9cix: true,
  },
});

Response

{
  "success": true,
  "id": "clw9h3y5a014yl70k9m2n4p8q"
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 400 Bad Request
{
  "success": false,
  "message": "An error message here."
}

findContact()

Find a contact.

API Reference

Parameters

You must use one parameter in the request.

Name Type Required Notes
email string No
userId string No

Examples

const resp = await loops.findContact({ email: "hello@gmail.com" });

const resp = await loops.findContact({ userId: "12345" });

Response

This method will return a list containing a single contact object, which will include all default properties and any custom properties.

If no contact is found, an empty list will be returned.

[
  {
    "id": "cll6b3i8901a9jx0oyktl2m4u",
    "email": "hello@gmail.com",
    "firstName": "Bob",
    "lastName": null,
    "source": "API",
    "subscribed": true,
    "userGroup": "",
    "userId": "12345",
    "mailingLists": {
      "cm06f5v0e45nf0ml5754o9cix": true
    },
    "optInStatus": null,
    "favoriteColor": "Blue" /* Custom property */
  }
]

deleteContact()

Delete a contact, either by email address or userId.

API Reference

Parameters

You must use one parameter in the request.

Name Type Required Notes
email string No
userId string No

Example

const resp = await loops.deleteContact({ email: "hello@gmail.com" });

const resp = await loops.deleteContact({ userId: "12345" });

Response

{
  "success": true,
  "message": "Contact deleted."
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 400 Bad Request
{
  "success": false,
  "message": "An error message here."
}
HTTP 404 Not Found
{
  "success": false,
  "message": "An error message here."
}

checkContactSuppression()

Check whether a contact is suppressed, either by email address or userId.

API Reference

Parameters

You must use one parameter in the request.

Name Type Required Notes
email string No
userId string No

Example

const resp = await loops.checkContactSuppression({ email: "hello@gmail.com" });

const resp = await loops.checkContactSuppression({ userId: "12345" });

Response

{
  "contact": {
    "id": "cll6b3i8901a9jx0oyktl2m4u",
    "email": "adam@loops.so",
    "userId": null
  },
  "isSuppressed": true,
  "removalQuota": {
    "limit": 100,
    "remaining": 4
  }
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 400 Bad Request
{
  "success": false,
  "message": "An email or userId is required."
}
HTTP 404 Not Found
{
  "success": false,
  "message": "This contact was not found."
}

removeContactSuppression()

Remove suppression for a contact, either by email address or userId.

API Reference

Parameters

You must use one parameter in the request.

Name Type Required Notes
email string No
userId string No

Example

const resp = await loops.removeContactSuppression({ email: "hello@gmail.com" });

const resp = await loops.removeContactSuppression({ userId: "12345" });

Response

{
  "success": true,
  "message": "Email removed from suppression list.",
  "removalQuota": {
    "limit": 100,
    "remaining": 4
  }
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 400 Bad Request
{
  "success": false,
  "message": "This contact is not suppressed."
}
HTTP 404 Not Found
{
  "success": false,
  "message": "This contact was not found."
}

createContactProperty()

Create a new contact property.

API Reference

Parameters

Name Type Required Notes
name string Yes The name of the property. Should be in camelCase, like planName or favouriteColor.
type string Yes The property's value type.
Can be one of string, number, boolean or date.

Examples

const resp = await loops.createContactProperty("planName", "string");

Response

{
  "success": true
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 400 Bad Request
{
  "success": false,
  "message": "An error message here."
}

listContactProperties()

Get a list of your account's contact properties.

API Reference

Parameters

Name Type Required Notes
list string No Use "custom" to retrieve only your account's custom properties.

Example

const resp = await loops.listContactProperties();

const resp = await loops.listContactProperties("custom");

Response

This method will return a list of contact property objects containing key, label and type attributes.

[
  {
    "key": "firstName",
    "label": "First Name",
    "type": "string"
  },
  {
    "key": "lastName",
    "label": "Last Name",
    "type": "string"
  },
  {
    "key": "email",
    "label": "Email",
    "type": "string"
  },
  {
    "key": "notes",
    "label": "Notes",
    "type": "string"
  },
  {
    "key": "source",
    "label": "Source",
    "type": "string"
  },
  {
    "key": "userGroup",
    "label": "User Group",
    "type": "string"
  },
  {
    "key": "userId",
    "label": "User Id",
    "type": "string"
  },
  {
    "key": "subscribed",
    "label": "Subscribed",
    "type": "boolean"
  },
  {
    "key": "createdAt",
    "label": "Created At",
    "type": "date"
  },
  {
    "key": "favoriteColor",
    "label": "Favorite Color",
    "type": "string"
  },
  {
    "key": "plan",
    "label": "Plan",
    "type": "string"
  }
]

listMailingLists()

Get a list of your account's mailing lists. Read more about mailing lists

API Reference

Parameters

None

Example

const resp = await loops.listMailingLists();

Response

This method will return a list of mailing list objects containing id, name, description and isPublic attributes.

If your account has no mailing lists, an empty list will be returned.

[
  {
    "id": "cm06f5v0e45nf0ml5754o9cix",
    "name": "Main list",
    "description": "All customers.",
    "isPublic": true
  },
  {
    "id": "cm16k73gq014h0mmj5b6jdi9r",
    "name": "Investors",
    "description": null,
    "isPublic": false
  }
]

sendEvent()

Send an event to trigger an email in Loops. Read more about events

API Reference

Parameters

Name Type Required Notes
email string No The contact's email address. Required if userId is not present.
userId string No The contact's unique user ID. If you use userId without email, this value must have already been added to your contact in Loops. Required if email is not present.
eventName string Yes
contactProperties object No An object containing contact properties, which will be updated or added to the contact when the event is received.
Please add custom properties in your Loops account before using them with the SDK.
Values can be of type string, number, null (to reset a value), boolean or date (see allowed date formats).
eventProperties object No An object containing event properties, which will be made available in emails that are triggered by this event.
Values can be of type string, number, boolean or date (see allowed date formats).
mailingLists object No An object of mailing list IDs and boolean subscription statuses.
headers object No Additional headers to send with the request.

Examples

const resp = await loops.sendEvent({
  email: "hello@gmail.com",
  eventName: "signup",
});

const resp = await loops.sendEvent({
  email: "hello@gmail.com",
  eventName: "signup",
  eventProperties: {
    username: "user1234",
    signupDate: "2024-03-21T10:09:23Z",
  },
  mailingLists: {
    cm06f5v0e45nf0ml5754o9cix: true,
    cm16k73gq014h0mmj5b6jdi9r: false,
  },
});

// In this case with both email and userId present, the system will look for a contact with either a
//  matching `email` or `userId` value.
// If a contact is found for one of the values (e.g. `email`), the other value (e.g. `userId`) will be updated.
// If a contact is not found, a new contact will be created using both `email` and `userId` values.
// Any values added in `contactProperties` will also be updated on the contact.
const resp = await loops.sendEvent({
  userId: "1234567890",
  email: "hello@gmail.com",
  eventName: "signup",
  contactProperties: {
    firstName: "Bob",
    plan: "pro",
  },
});

// Example with Idempotency-Key header
const resp = await loops.sendEvent({
  email: "hello@gmail.com",
  eventName: "signup",
  headers: {
    "Idempotency-Key": "550e8400-e29b-41d4-a716-446655440000",
  },
});

Response

{
  "success": true
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 400 Bad Request
{
  "success": false,
  "message": "An error message here."
}

sendTransactionalEmail()

Send a transactional email to a contact. Learn about sending transactional email

API Reference

Parameters

Name Type Required Notes
transactionalId string Yes The ID of the transactional email to send.
email string Yes The email address of the recipient.
addToAudience boolean No If true, a contact will be created in your audience using the email value (if a matching contact doesn’t already exist).
dataVariables object No An object containing data as defined by the data variables added to the transactional email template.
Values can be of type string, number, or an array of objects with string or number values.
attachments object[] No A list of attachments objects.
Please note: Attachments need to be enabled on your account before using them with the API. Read more
attachments[].filename string No The name of the file, shown in email clients.
attachments[].contentType string No The MIME type of the file.
attachments[].data string No The base64-encoded content of the file.
headers object No Additional headers to send with the request.

Examples

const resp = await loops.sendTransactionalEmail({
  transactionalId: "clfq6dinn000yl70fgwwyp82l",
  email: "hello@gmail.com",
  dataVariables: {
    loginUrl: "https://myapp.com/login/",
  },
});

// Example with Idempotency-Key header
const resp = await loops.sendTransactionalEmail({
  transactionalId: "clfq6dinn000yl70fgwwyp82l",
  email: "hello@gmail.com",
  dataVariables: {
    loginUrl: "https://myapp.com/login/",
  },
  headers: {
    "Idempotency-Key": "550e8400-e29b-41d4-a716-446655440000",
  },
});

// Please contact us to enable attachments on your account.
const resp = await loops.sendTransactionalEmail({
  transactionalId: "clfq6dinn000yl70fgwwyp82l",
  email: "hello@gmail.com",
  dataVariables: {
    loginUrl: "https://myapp.com/login/",
  },
  attachments: [
    {
      filename: "presentation.pdf",
      contentType: "application/pdf",
      data: "JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPD...",
    },
  ],
});

Response

{
  "success": true
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 400 Bad Request
{
  "success": false,
  "path": "dataVariables",
  "message": "There are required fields for this email. You need to include a 'dataVariables' object with the required fields."
}
HTTP 400 Bad Request
{
  "success": false,
  "error": {
    "path": "dataVariables",
    "message": "Missing required fields: login_url"
  },
  "transactionalId": "clfq6dinn000yl70fgwwyp82l"
}

listTransactionalEmails()

Get a paginated list of transactional emails, most recently created first.

API Reference

Parameters

Name Type Required Notes
perPage integer No How many results to return per page. Must be between 10 and 50. Defaults to 20 if omitted.
cursor string No A cursor, to return a specific page of results. Cursors can be found from the pagination.nextCursor value in each response.

Example

const resp = await loops.listTransactionalEmails();

const resp = await loops.listTransactionalEmails({ perPage: 15 });

Response

{
  "pagination": {
    "totalResults": 23,
    "returnedResults": 20,
    "perPage": 20,
    "totalPages": 2,
    "nextCursor": "clyo0q4wo01p59fsecyxqsh38",
    "nextPage": "https://app.loops.so/api/v1/transactional-emails?cursor=clyo0q4wo01p59fsecyxqsh38&perPage=20"
  },
  "data": [
    {
      "id": "clfn0k1yg001imo0fdeqg30i8",
      "name": "Sign up confirmation",
      "draftEmailMessageId": null,
      "publishedEmailMessageId": "clm9x3o5q002yl70a8b3c4d5e",
      "transactionalGroupId": null,
      "createdAt": "2023-11-06T17:48:07.249Z",
      "updatedAt": "2023-11-06T17:48:07.249Z",
      "dataVariables": []
    },
    {
      "id": "cll42l54f20i1la0lfooe3z12",
      "name": "Password reset",
      "draftEmailMessageId": "clm8k2n4p000yl70f6g7h8i9j",
      "publishedEmailMessageId": "clm8k2n4p001yl70k1l2m3n4o",
      "transactionalGroupId": "clq3b7s9u006yl70p5q6r7s8t",
      "createdAt": "2025-02-02T02:56:28.845Z",
      "updatedAt": "2025-02-02T02:56:28.845Z",
      "dataVariables": [
        "confirmationUrl"
      ]
    },
    ...
  ]
}

getTransactionalEmail()

Retrieve a single transactional email by ID.

API Reference

Parameters

Name Type Required Notes
transactionalId string Yes The ID of the transactional email.

Example

const resp = await loops.getTransactionalEmail("clfn0k1yg001imo0fdeqg30i8");

createTransactionalEmail()

Create a new transactional email. An empty draft email message is created automatically.

API Reference

Parameters

Name Type Required Notes
name string Yes The name of the transactional email.
transactionalGroupId string No The ID of the group to add this transactional email to. Defaults to the team's default group.

Example

const resp = await loops.createTransactionalEmail({ name: "Welcome email" });

updateTransactionalEmail()

Update a transactional email by ID. At least one field is required.

API Reference

Parameters

Name Type Required Notes
transactionalId string Yes The ID of the transactional email.
name string No The name of the transactional email.
transactionalGroupId string No The ID of the group to move this transactional email to.

Example

const resp = await loops.updateTransactionalEmail("clfn0k1yg001imo0fdeqg30i8", {
  name: "Updated name",
});

const resp = await loops.updateTransactionalEmail("clfn0k1yg001imo0fdeqg30i8", {
  transactionalGroupId: "clq3b7s9u006yl70p5q6r7s8t",
});

ensureTransactionalEmailDraft()

Ensure a transactional email has a draft email message. Use updateEmailMessage() to edit the draft content.

API Reference

Parameters

Name Type Required Notes
transactionalId string Yes The ID of the transactional email.

Example

const resp = await loops.ensureTransactionalEmailDraft("clfn0k1yg001imo0fdeqg30i8");

publishTransactionalEmail()

Publish a transactional email's current draft.

API Reference

Parameters

Name Type Required Notes
transactionalId string Yes The ID of the transactional email.

Example

const resp = await loops.publishTransactionalEmail("clfn0k1yg001imo0fdeqg30i8");

listDedicatedSendingIps()

Get a list of Loops' dedicated sending IP addresses. This is intended for rare cases where you need to whitelist Loops' sending IPs.

API Reference

Parameters

None

Example

const resp = await loops.listDedicatedSendingIps();

Response

[
  "1.2.3.4",
  "5.6.7.8"
]

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.


listThemes()

Retrieve a paginated list of email themes, most recently created first. API Reference

Parameters

Name Type Required Notes
perPage integer No How many results to return per page. Must be between 10 and 50. Defaults to 20 if omitted.
cursor string No A cursor, to return a specific page of results. Cursors can be found from the pagination.nextCursor value in each response.

Example

const resp = await loops.listThemes();

const resp = await loops.listThemes({ perPage: 15, cursor: "clyo0q4wo01p59fsecyxqsh38" });

Response

{
  "pagination": {
    "totalResults": 1,
    "returnedResults": 1,
    "perPage": 20,
    "totalPages": 1,
    "nextCursor": null,
    "nextPage": null
  },
  "data": [
    {
      "id": "clo1z5q7s004yl70y3z4a5b6c",
      "name": "Default",
      "styles": {
        "backgroundColor": "#ffffff"
      },
      "isDefault": true,
      "createdAt": "2025-01-01T00:00:00.000Z",
      "updatedAt": "2025-01-01T00:00:00.000Z"
    }
  ]
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.


getTheme()

Retrieve a single theme by ID. API Reference

Parameters

Name Type Required Notes
themeId string Yes The ID of the theme.

Example

const resp = await loops.getTheme("clo1z5q7s004yl70y3z4a5b6c");

Response

{
  "id": "clo1z5q7s004yl70y3z4a5b6c",
  "name": "Default",
  "styles": {
    "backgroundColor": "#ffffff"
  },
  "isDefault": true,
  "createdAt": "2025-01-01T00:00:00.000Z",
  "updatedAt": "2025-01-01T00:00:00.000Z"
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.


listComponents()

Retrieve a paginated list of email components. API Reference

Parameters

Name Type Required Notes
perPage integer No How many results to return per page. Must be between 10 and 50. Defaults to 20 if omitted.
cursor string No A cursor, to return a specific page of results. Cursors can be found from the pagination.nextCursor value in each response.

Example

const resp = await loops.listComponents();

const resp = await loops.listComponents({ perPage: 15 });

Response

{
  "pagination": {
    "totalResults": 1,
    "returnedResults": 1,
    "perPage": 20,
    "totalPages": 1,
    "nextCursor": null,
    "nextPage": null
  },
  "data": [
    {
      "id": "clp2a6r8t005yl70d7e8f9g0h",
      "name": "Header",
      "lmx": "<Section>...</Section>"
    }
  ]
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.


getComponent()

Retrieve a single component by ID. API Reference

Parameters

Name Type Required Notes
componentId string Yes The ID of the component.

Example

const resp = await loops.getComponent("clp2a6r8t005yl70d7e8f9g0h");

Response

{
  "id": "clp2a6r8t005yl70d7e8f9g0h",
  "name": "Header",
  "lmx": "<Section>...</Section>"
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.


listCampaigns()

Retrieve a paginated list of campaigns. API Reference

Parameters

Name Type Required Notes
perPage integer No How many results to return per page. Must be between 10 and 50. Defaults to 20 if omitted.
cursor string No A cursor, to return a specific page of results. Cursors can be found from the pagination.nextCursor value in each response.

Example

const resp = await loops.listCampaigns();

const resp = await loops.listCampaigns({ perPage: 15 });

Response

{
  "pagination": {
    "totalResults": 1,
    "returnedResults": 1,
    "perPage": 20,
    "totalPages": 1,
    "nextCursor": null,
    "nextPage": null
  },
  "data": [
    {
      "id": "cln0y4p6r003yl70i1j2k3l4m",
      "emailMessageId": "clm9x3o5q002yl70a8b3c4d5e",
      "name": "Spring announcement",
      "status": "Draft",
      "createdAt": "2025-01-01T00:00:00.000Z",
      "updatedAt": "2025-01-01T00:00:00.000Z",
      "campaignGroupId": null,
      "mailingListId": null,
      "audienceSegmentId": null,
      "audienceFilter": null,
      "scheduling": {
        "method": "now",
        "timestamp": null
      }
    }
  ]
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.


createCampaign()

Create a new draft campaign. An empty email message is created automatically and its emailMessageId is returned. Use updateEmailMessage() to set subject, sender, preview text, and LMX content. The audience (mailing list, segment, or filter), group, and scheduling can be set on create or later via update. API Reference

Parameters

Name Type Required Notes
name string Yes The campaign name.
campaignGroupId string No The ID of the group to add this campaign to.
mailingListId string No The ID of the mailing list to send to.
audienceSegmentId string No The ID of an audience segment. Setting this clears any audienceFilter.
audienceFilter object No An audience filter object. See the API reference.
scheduling object No When the campaign should send (method: now or schedule, with optional timestamp).

Example

const resp = await loops.createCampaign({ name: "Spring announcement" });

const resp = await loops.createCampaign({
  name: "Spring announcement",
  mailingListId: "cm06f5v0e45nf0ml5754o9cix",
  scheduling: { method: "schedule", timestamp: "2026-06-15T10:00:00.000Z" },
});

Response

{
  "id": "cln0y4p6r003yl70i1j2k3l4m",
  "name": "Spring announcement",
  "status": "Draft",
  "createdAt": "2025-01-01T00:00:00.000Z",
  "updatedAt": "2025-01-01T00:00:00.000Z",
  "emailMessageId": "clm9x3o5q002yl70a8b3c4d5e",
  "emailMessageContentRevisionId": "clv8g2x4z012yl70n5o6p7q8r",
  "campaignGroupId": null,
  "mailingListId": null,
  "audienceSegmentId": null,
  "audienceFilter": null,
  "scheduling": {
    "method": "now",
    "timestamp": null
  }
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.


getCampaign()

Retrieve a single campaign by ID. API Reference

Parameters

Name Type Required Notes
campaignId string Yes The ID of the campaign.

Example

const resp = await loops.getCampaign("cln0y4p6r003yl70i1j2k3l4m");

Response

{
  "id": "cln0y4p6r003yl70i1j2k3l4m",
  "name": "Spring announcement",
  "status": "Draft",
  "createdAt": "2025-01-01T00:00:00.000Z",
  "updatedAt": "2025-01-01T00:00:00.000Z",
  "emailMessageId": "clm9x3o5q002yl70a8b3c4d5e",
  "campaignGroupId": null,
  "mailingListId": null,
  "audienceSegmentId": null,
  "audienceFilter": null,
  "scheduling": {
    "method": "now",
    "timestamp": null
  }
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.


updateCampaign()

Update a draft campaign's name, group, audience, or scheduling. At least one field must be provided. Campaigns can only be updated while in draft status. API Reference

Parameters

Name Type Required Notes
campaignId string Yes The ID of the campaign.
name string No The campaign name.
campaignGroupId string No The ID of the group to move this campaign to.
mailingListId string No The ID of the mailing list to send to.
audienceSegmentId string No The ID of an audience segment. Setting this clears any audienceFilter.
audienceFilter object No An audience filter object.
scheduling object No When the campaign should send. At least one field is required.

Example

const resp = await loops.updateCampaign("cln0y4p6r003yl70i1j2k3l4m", { name: "Updated name" });

Response

{
  "id": "cln0y4p6r003yl70i1j2k3l4m",
  "name": "Updated name",
  "status": "Draft",
  "createdAt": "2025-01-01T00:00:00.000Z",
  "updatedAt": "2025-01-02T00:00:00.000Z",
  "emailMessageId": "clm9x3o5q002yl70a8b3c4d5e",
  "campaignGroupId": null,
  "mailingListId": null,
  "audienceSegmentId": null,
  "audienceFilter": null,
  "scheduling": {
    "method": "now",
    "timestamp": null
  }
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 409 Conflict
{
  "success": false,
  "message": "Campaign is not in draft status."
}

getEmailMessage()

Retrieve an email message, including its compiled LMX content. API Reference

Parameters

Name Type Required Notes
emailMessageId string Yes The ID of the email message.

Example

const resp = await loops.getEmailMessage("clm9x3o5q002yl70a8b3c4d5e");

Response

{
  "id": "clm9x3o5q002yl70a8b3c4d5e",
  "campaignId": "cln0y4p6r003yl70i1j2k3l4m",
  "subject": "Hello",
  "previewText": "Preview text",
  "fromName": "Loops",
  "fromEmail": "hello",
  "replyToEmail": "",
  "emailFormat": "styled",
  "lmx": "<Email>...</Email>",
  "contentRevisionId": "clv8g2x4z012yl70n5o6p7q8r",
  "updatedAt": "2025-01-01T00:00:00.000Z"
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.


updateEmailMessage()

Update fields on an email message (subject, preview text, sender, LMX content). The campaign must be in draft status. Supply expectedRevisionId matching the current contentRevisionId — the server rejects mismatched revisions with 409. API Reference

Parameters

Name Type Required Notes
emailMessageId string Yes The ID of the email message.
expectedRevisionId string No The contentRevisionId you last fetched. Used for optimistic concurrency.
subject string No The email subject.
previewText string No The email preview text.
fromName string No The sender name.
fromEmail string No The sender username (without @ or domain). The team's sending domain is appended automatically.
replyToEmail string No Reply-to email. Must be empty or a valid email address.
ccEmail string No CC email address. Requires CC/BCC to be enabled for your team.
bccEmail string No BCC email address. Requires CC/BCC to be enabled for your team.
languageCode string No Language code for the email. Requires translation to be enabled for your team.
emailFormat string No The rendering format: styled or plain.
lmx string No The email body serialized as LMX. Styles must be embedded in the LMX <Style /> tag.
contactPropertiesFallbacks object No Fallback values for contact properties, keyed by property name.
eventPropertiesFallbacks object No Fallback values for event properties, keyed by property name.
dataVariablesFallbacks object No Fallback values for data variables, keyed by variable name.

Example

const resp = await loops.updateEmailMessage("clm9x3o5q002yl70a8b3c4d5e", {
  expectedRevisionId: "clv8g2x4z012yl70n5o6p7q8r",
  subject: "Hello",
  previewText: "Preview text",
  fromName: "Loops",
  fromEmail: "hello",
  lmx: "<Email>...</Email>",
});

Response

{
  "id": "clm9x3o5q002yl70a8b3c4d5e",
  "campaignId": "cln0y4p6r003yl70i1j2k3l4m",
  "subject": "Hello",
  "previewText": "Preview text",
  "fromName": "Loops",
  "fromEmail": "hello",
  "replyToEmail": "",
  "emailFormat": "styled",
  "lmx": "<Email>...</Email>",
  "contentRevisionId": "clv8g2x4z013yl70s9t0u1v2w",
  "updatedAt": "2025-01-02T00:00:00.000Z",
  "warnings": [
    {
      "rule": "example",
      "severity": "warning",
      "message": "Example warning"
    }
  ]
}

Error handling is done through the APIError class, which provides statusCode and json properties containing the API's error response details. For implementation examples, see the Usage section.

HTTP 409 Conflict
{
  "success": false,
  "message": "Content revision ID is stale."
}

listTransactionalGroups()

Retrieve a paginated list of transactional groups. API Reference

Parameters

Name Type Required Notes
perPage integer No How many results to return per page. Must be between 10 and 50. Defaults to 20 if omitted.
cursor string No A cursor, to return a specific page of results. Cursors can be found from the pagination.nextCursor value in each response.

Example

const resp = await loops.listTransactionalGroups();

createTransactionalGroup()

Create a new transactional group. API Reference

Parameters

Name Type Required Notes
name string Yes The group name. Cannot be "Unsorted".
description string No An optional description for the group.

Example

const resp = await loops.createTransactionalGroup({
  name: "Onboarding",
  description: "Transactional emails for new users",
});

getTransactionalGroup()

Retrieve a single transactional group by ID. API Reference

Parameters

Name Type Required Notes
transactionalGroupId string Yes The ID of the transactional group.

Example

const resp = await loops.getTransactionalGroup("clq3b7s9u006yl70p5q6r7s8t");

updateTransactionalGroup()

Update a transactional group's name or description. At least one field must be provided. The reserved "Unsorted" group cannot be edited. API Reference

Parameters

Name Type Required Notes
transactionalGroupId string Yes The ID of the transactional group.
name string No The group name.
description string No A description for the group.

Example

const resp = await loops.updateTransactionalGroup("clq3b7s9u006yl70p5q6r7s8t", {
  name: "Updated name",
});

listAudienceSegments()

Retrieve a paginated list of audience segments. API Reference

Parameters

Name Type Required Notes
perPage integer No How many results to return per page. Must be between 10 and 50. Defaults to 20 if omitted.
cursor string No A cursor, to return a specific page of results. Cursors can be found from the pagination.nextCursor value in each response.

Example

const resp = await loops.listAudienceSegments();

getAudienceSegment()

Retrieve a single audience segment by ID. API Reference

Parameters

Name Type Required Notes
audienceSegmentId string Yes The ID of the audience segment.

Example

const resp = await loops.getAudienceSegment("clr4c8t0v008yl70x3y4z5a6b");

listCampaignGroups()

Retrieve a paginated list of campaign groups. API Reference

Parameters

Name Type Required Notes
perPage integer No How many results to return per page. Must be between 10 and 50. Defaults to 20 if omitted.
cursor string No A cursor, to return a specific page of results. Cursors can be found from the pagination.nextCursor value in each response.

Example

const resp = await loops.listCampaignGroups();

createCampaignGroup()

Create a new campaign group. API Reference

Parameters

Name Type Required Notes
name string Yes The group name. Cannot be "Unsorted".
description string No An optional description for the group.

Example

const resp = await loops.createCampaignGroup({
  name: "Newsletters",
});

getCampaignGroup()

Retrieve a single campaign group by ID. API Reference

Parameters

Name Type Required Notes
campaignGroupId string Yes The ID of the campaign group.

Example

const resp = await loops.getCampaignGroup("clq3b7s9u007yl70u9v0w1x2y");

updateCampaignGroup()

Update a campaign group's name or description. At least one field must be provided. The reserved "Unsorted" group cannot be edited. API Reference

Parameters

Name Type Required Notes
campaignGroupId string Yes The ID of the campaign group.
name string No The group name.
description string No A description for the group.

Example

const resp = await loops.updateCampaignGroup("clq3b7s9u007yl70u9v0w1x2y", {
  description: "Monthly product updates",
});

sendEmailMessagePreview()

Send a test preview of an email message to one or more addresses. API Reference

Parameters

Name Type Required Notes
emailMessageId string Yes The ID of the email message.
emails string[] Yes One or more addresses to send the preview to.
contactProperties object No Contact property values to render. Accepted for campaign and workflow previews.
eventProperties object No Event property values to render. Accepted for workflow previews only.
dataVariables object No Transactional data variables to render. Accepted for transactional previews only.

Example

const resp = await loops.sendEmailMessagePreview("clm9x3o5q002yl70a8b3c4d5e", {
  emails: ["test@example.com"],
  contactProperties: {
    firstName: "Alex",
  },
});

listWorkflows()

Retrieve a paginated list of workflows. API Reference

Parameters

Name Type Required Notes
perPage integer No How many results to return per page. Must be between 10 and 50. Defaults to 20 if omitted.
cursor string No A cursor, to return a specific page of results. Cursors can be found from the pagination.nextCursor value in each response.

Example

const resp = await loops.listWorkflows();

getWorkflow()

Retrieve a workflow graph with node type names, connections, and selected display fields. API Reference

Parameters

Name Type Required Notes
workflowId string Yes The ID of the workflow.

Example

const resp = await loops.getWorkflow("cls5d9u1w009yl70c7d8e9f0g");

getWorkflowNode()

Retrieve detailed data for a single workflow node. API Reference

Parameters

Name Type Required Notes
workflowId string Yes The ID of the workflow.
nodeId string Yes The ID of the workflow node.

Example

const resp = await loops.getWorkflowNode("cls5d9u1w009yl70c7d8e9f0g", "clt6e0v2x010yl70h1i2j3k4l");

createUpload()

Request a pre-signed URL to upload an image asset. Upload the file with an HTTP PUT to the returned presignedUrl, then call completeUpload().

API Reference

Parameters

Name Type Required Notes
contentType string Yes MIME type (image/jpeg, image/png, image/gif, or image/webp).
contentLength integer Yes File size in bytes. Must be a positive integer no greater than 4,000,000 bytes.

Example

const resp = await loops.createUpload({
  contentType: "image/png",
  contentLength: 102400,
});

completeUpload()

Finalize an asset after the file has been uploaded to the pre-signed URL.

API Reference

Parameters

Name Type Required Notes
id string Yes The emailAssetId returned from createUpload().

Example

const resp = await loops.completeUpload("clu7f1w3y011yl70m5n6o7p8q");

Version history


Tests

Run tests with npm run test.


Contributing

Bug reports and pull requests are welcome. Please read our Contributing Guidelines.

About

The Official Loops JavaScript SDK

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Contributors