Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

loops

Package Overview
Dependencies
Maintainers
2
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

loops

## Introduction

  • 3.4.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
17K
increased by2.99%
Maintainers
2
Weekly downloads
 
Created
Source

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 } from "loops";

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

const resp = await loops.createContact("email@provider.com");

## 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, 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

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

This method will return a success or error message:

{
  "success": true,
  "teamName": "My team"
}
{
  "error": "Invalid API key"
}

createContact()

Create a new contact.

API Reference

Parameters
NameTypeRequiredNotes
emailstringYesIf a contact already exists with this email address, an error response will be returned.
propertiesobjectNoAn 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).
mailingListsobjectNoAn object of mailing list IDs and boolean subscription statuses.
Examples
const resp = await loops.createContact("hello@gmail.com");

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

This method will return a success or error message:

{
  "success": true,
  "id": "id_of_contact"
}
{
  "success": false,
  "message": "An error message here."
}

updateContact()

Update a contact.

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
NameTypeRequiredNotes
emailstringYesThe 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.
propertiesobjectNoAn 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).
mailingListsobjectNoAn object of mailing list IDs and boolean subscription statuses.
Example
const contactProperties = {
  firstName: "Bob" /* Default property */,
  favoriteColor: "Blue" /* Custom property */,
};
const resp = await loops.updateContact("hello@gmail.com", contactProperties);

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

This method will return a success or error message:

{
  "success": true,
  "id": "id_of_contact"
}
{
  "success": false,
  "message": "An error message here."
}

findContact()

Find a contact.

API Reference

Parameters

You must use one parameter in the request.

NameTypeRequiredNotes
emailstringNo
userIdstringNo
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
    },
    "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.

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

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

This method will return a success or error message:

{
  "success": true,
  "message": "Contact deleted."
}
{
  "success": false,
  "message": "An error message here."
}

getMailingLists()

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

API Reference

Parameters

None

Example
const resp = await loops.getMailingLists();
Response

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

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

[
  {
    "id": "cm06f5v0e45nf0ml5754o9cix",
    "name": "Main list",
    "isPublic": true
  },
  {
    "id": "cm16k73gq014h0mmj5b6jdi9r",
    "name": "Investors",
    "isPublic": false
  }
]

sendEvent()

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

API Reference

Parameters
NameTypeRequiredNotes
emailstringNoThe contact's email address. Required if userId is not present.
userIdstringNoThe 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.
eventNamestringYes
contactPropertiesobjectNoAn 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).
eventPropertiesobjectNoAn object containing event properties, which will be made availabe in emails that are triggered by this event.
Values can be of type string, number, boolean or date (see allowed date formats).
mailingListsobjectNoAn object of mailing list IDs and boolean subscription statuses.
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",
  },
});
Response

This method will return a success or error:

{
  "success": true
}
{
  "success": false,
  "message": "An error message here."
}

sendTransactionalEmail()

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

API Reference

Parameters
NameTypeRequiredNotes
transactionalIdstringYesThe ID of the transactional email to send.
emailstringYesThe email address of the recipient.
addToAudiencebooleanNoIf true, a contact will be created in your audience using the email value (if a matching contact doesn’t already exist).
dataVariablesobjectNoAn object containing data as defined by the data variables added to the transactional email template.
Values can be of type string or number.
attachmentsobject[]NoA list of attachments objects.
Please note: Attachments need to be enabled on your account before using them with the API. Read more
attachments[].filenamestringNoThe name of the file, shown in email clients.
attachments[].contentTypestringNoThe MIME type of the file.
attachments[].datastringNoThe base64-encoded content of the file.
Examples
const resp = await loops.sendTransactionalEmail({
  transactionalId: "clfq6dinn000yl70fgwwyp82l",
  email: "hello@gmail.com",
  dataVariables: {
    loginUrl: "https://myapp.com/login/",
  },
});

// 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

This method will return a success or error message.

{
  "success": true
}

If there is a problem with the request, a descriptive error message will be returned:

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

getCustomFields()

Get a list of your account's custom fields. These are custom properties that can be added to contacts to store extra data. Read more about contact properties

API Reference

Parameters

None

Example
const resp = await loops.getCustomFields();
Response

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

If your account has no custom fields, an empty list will be returned.

[
  {
    "key": "favoriteColor",
    "label": "Favorite Color",
    "type": "string"
  },
  {
    "key": "plan",
    "label": "Plan",
    "type": "string"
  }
]

Version history

  • v3.4.0 (Oct 29, 2024) - Added rate limit handling with RateLimitExceededError.
  • v3.3.0 (Sep 9, 2024) - Added testApiKey() method.
  • v3.2.0 (Aug 23, 2024) - Added support for a new mailingLists attribute in findContact().
  • v3.1.1 (Aug 16, 2024) - Support for a new isPublic attribute in getMailingLists().
  • v3.1.0 (Aug 12, 2024) - The SDK now accepts null as a value for contact properties in createContact(), updateContact() and sendEvent(), which allows you to reset/empty properties.
  • v3.0.0 (Jul 2, 2024) - sendTransactionalEmail() now accepts an object instead of separate parameters (breaking change).
  • v2.2.0 (Jul 2, 2024) - Deprecated. Added new addToAudience option to sendTransactionalEmail().
  • v2.1.1 (Jun 20, 2024) - Added support for mailing lists in createContact(), updateContact() and sendEvent().
  • v2.1.0 (Jun 19, 2024) - Added support for new List mailing lists endpoint.
  • v2.0.0 (Apr 19, 2024)
    • Added userId as a parameter to findContact(). This includes a breaking change for the findContact() parameters.
    • userId values must now be strings (could have also been numbers previously).
  • v1.0.1 (Apr 1, 2024) - Fixed types for sendEvent().
  • v1.0.0 (Mar 28, 2024) - Fix for ESM types. Switched to named export.
  • v0.4.0 (Mar 22, 2024) - Support for new eventProperties in sendEvent(). This includes a breaking change for the sendEvent() parameters.
  • v0.3.0 (Feb 22, 2024) - Updated minimum Node version to 18.0.0.
  • v0.2.1 (Feb 6, 2024) - Fix for ESM imports.
  • v0.2.0 (Feb 1, 2024) - CommonJS support.
  • v0.1.5 (Jan 25, 2024) - getCustomFields() now returns type values for each contact property.
  • v0.1.4 (Jan 25, 2024) - Added support for userId in sendEvent() request. Added missing error response type for sendEvent() requests.
  • v0.1.3 (Dec 8, 2023) - Added support for transactional attachments.
  • v0.1.2 (Dec 6, 2023) - Improved transactional error types.
  • v0.1.1 (Nov 1, 2023) - Initial release.

Contributing

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

FAQs

Package last updated on 29 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc