---
updatedAt: 2026-03-06T13:59:37.000Z
agentTools:
  projectIndex: https://docs.pelcro.com/v2.4/llms.txt
---

# JavaScript SDK

Pelcro JavaScript SDK empowers businesses to provide users with a seamless experience in a matter of minutes.

Include the Pelcro.js script on every page of your site. To ensure you always receive the latest features and security updates, you must load the Pelcro.js script directly from <code><https://js.pelcro.com></code>. <strong>Do not bundle the script or host it yourself</strong>, as this will prevent you from receiving critical updates.

<Callout icon="" theme="warn">
  To protect the security and stability of our platform, we reserve the right to block traffic from outdated and unsupported versions of the SDK. Self-hosting or bundling the script will eventually lead to your integration becoming outdated, which could cause it to stop working without notice.
</Callout>

***

## Including Pelcro.js

To install the SDK, copy and paste the code below on every page of your site. You can find your configured script on the integration page from the settings of the platform.

### Recommended Snippet

#### Production

```html
<script>
  window.Pelcro = {};
  window.Pelcro.siteid = 1232; // replace with your PRODUCTION Site ID
  window.Pelcro.environment = {
    domain: "https://www.pelcro.com",
    ui: "https://ui.pelcro.com/bundle.js",
    stripe: "pk_live_Wdef2LjEQXsgFWult6IVFobB"
  };
</script>
<script defer src="https://js.pelcro.com/sdk/main.min.js" type="text/javascript"></script>
```

#### Staging

```html
<script>
  window.Pelcro = {};
  window.Pelcro.siteid = 1232; // replace with your STAGING Site ID
  window.Pelcro.environment = {
    domain: "https://staging.pelcro.com",
    ui: "https://ui.pelcro.com/staging/bundle.js",
    stripe: "pk_test_aThAAdvPHgIdAziZweywBWNk"
  };
</script>
<script defer src="https://js.pelcro.com/sdk/staging/main.min.js" type="text/javascript"></script>
```

### Optional UI Settings

```html
<script>
  window.Pelcro.uiSettings = {
    // Analytics
    enableReactGA4: false,

    // Newsletter Configuration
    newsletters: [
      {"id": "newsletter_1", "label": "Daily Newsletter"},
      {"id": "newsletter_2", "label": "Weekly Digest"}
    ],

    // Email Notification Preferences
    emailNotifications: [
      {"id": "marketing", "label": "Marketing Emails"},
      {"id": "updates", "label": "Product Updates"}
    ]
  };
</script>
```

### UI Settings Reference

| Parameter                               | Description                                                                                                                                                             |
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enableReactGA4`                        | Enables Google Analytics 4 tracking for UI events. Set to `true` to track user interactions and events.                                                                 |
| `uiVersion`                             | Specifies the UI version for tracking and compatibility purposes. Used to identify which version of the UI is being used.                                               |
| `enableLoginWithUsername`               | Allows users to log in with a username instead of email only. When `true`, adds a username field to login and user profile forms.                                       |
| `enableNameFieldsInRegister`            | Shows first name and last name fields in the registration form. Set to `true` to collect user names during registration.                                                |
| `requireNameFieldsInRegister`           | Makes name fields mandatory during registration. Only works when `enableNameFieldsInRegister` is `true`.                                                                |
| `enableDateOfBirth`                     | Shows date of birth field in the user profile update form. Set to `true` to allow users to add or edit their date of birth.                                             |
| `addNewslettersSelectionToRegistration` | Adds newsletter subscription checkboxes to the registration form. Requires `newsletters` array to be defined.                                                           |
| `skipPaymentForFreePlans`               | Bypasses payment method collection for free or zero-cost plans. When `true`, users can subscribe to free plans without entering payment details.                        |
| `hideGiftForAutoRenew`                  | Hides the gift subscription option for auto-renewing plans. Set to `true` to prevent gifting of recurring subscriptions.                                                |
| `newsletters`                           | Array of available newsletters with `id` and `label` properties. Example: `[{"id": "daily", "label": "Daily Newsletter"}]`. Used in registration and preferences.       |
| `emailNotifications`                    | Array of email notification categories with `id` and `label` properties. Example: `[{"id": "marketing", "label": "Marketing Emails"}]`. Used in preferences management. |

***

## Placement in Your HTML

For the best performance and user experience, you should always include Pelcro.js in the `<head>` of your pages, with defer. Loading the script in the head ensures that the SDK download begins immediately while the browser is parsing your HTML, reducing the delay before Pelcro is ready. By including the defer attribute, you prevent the script from blocking rendering, since it will only execute once the DOM has finished parsing. This combination achieves the fastest and most predictable initialization of Pelcro features such as paywalls, login prompts, and offers.

<Callout icon="" theme="warn">
  If you load the SDK at the bottom of `<body>`, the UI will only initialize after the entire page finishes rendering, adding visible delay before modals or paywalls appear.
</Callout>

***

## Optimizing with Preconnect

To speed up Pelcro's initialization, you can add preconnect hints in the `<head>` of your pages. Preconnect establishes early network connections (DNS, TCP, TLS) to Pelcro's servers and other third-party services, so that when the SDK or UI bundle is requested, the browser can start downloading immediately instead of waiting to set up a new connection.

```html
<!-- Resource hints -->
<link rel="preconnect" href="https://js.pelcro.com" crossorigin>
<link rel="preconnect" href="https://ui.pelcro.com" crossorigin>
<link rel="preconnect" href="https://www.pelcro.com" crossorigin>

<!-- If you process payments with Stripe -->
<link rel="preconnect" href="https://js.stripe.com" crossorigin>
<link rel="preconnect" href="https://m.stripe.network" crossorigin>

```

**Why it matters**: Preconnect can save hundreds of milliseconds on first-time visits, reducing the time it takes for Pelcro modals and paywalls to appear. Place these tags before your Pelcro configuration and SDK script. They are safe to include on all pages, even if Pelcro is not used everywhere - browsers only establish the connections they need.

***

## Browser Support

Our SDK supports all recent versions of major browsers on desktop and mobile, covering **92% of global browser usage**. To ensure the best security, performance and user experience, we do not support legacy browsers without security updates.

### Supported

* **Chrome, Firefox, Safari, and Edge**: Latest versions plus the previous major version.
* **Mobile browsers**: Recent versions of Chrome Mobile, Safari Mobile, Samsung Internet, and other modern mobile browsers.

### Not Supported

* Internet Explorer 11 and earlier.
* Browsers without security updates for 24+ months.
* Browsers that don't support modern JavaScript features (ES6 modules, Promises, TLS 1.2).

### Technical Requirements

For browsers not explicitly supported, we require a modern environment that includes support for TLS 1.2, JavaScript Promises, and ES6 module loading. While our SDK may work on other browsers, we do not proactively test them but may respond to bug reports.

If you have an issue with our JavaScript SDK on a specific browser, please contact us so we can improve its support.

***

## Modules

The SDK exposes modules on the global `Pelcro` object. All async methods follow the callback pattern `(error, data) => {}`, and synchronous methods return cached data directly.

```javascript
// Async action
Pelcro.user.login({ email, password }, (err, user) => {
  if (user) console.log("Logged in:", user.email);
});

// Sync read
const site = Pelcro.site.read();

// Boolean check
if (Pelcro.user.isAuthenticated()) { /* ... */ }
```

Available modules: **Site**, **User**, **Location**, **Paywall**, **Subscription**, **Plan**, **Membership**, **Payment Source**, **Payment Method**, **Invoice**, **Coupon**, **Ecommerce**, **Product**, **Order**, **Address**, **Password**, **Newsletter**, **Campaign**, and **Insight**.

For the complete reference with all methods, parameters, return values, and events fired, see the [Modules Reference](javascript-sdk-modules).

***

## Events

The SDK dispatches custom DOM events that you can listen to for integrating analytics, customizing the user experience, or triggering your own logic.

```javascript
document.addEventListener("PelcroUserLoggedIn", (event) => {
  console.log("User logged in:", event.detail);
});

document.addEventListener("PelcroSubscriptionCreated", (event) => {
  console.log("New subscription:", event.detail);
});
```

For the complete list of all events, their payloads, firing conditions, and boot sequence, see the [Events Reference](javascript-sdk-events).

***

## Helpers

Utility methods available on `window.Pelcro.helpers`.

### getURLParameter

`Pelcro.helpers.getURLParameter(name)`

Gets a URL query parameter value from the current page URL.

| Parameter | Type   | Required | Description          |
| --------- | ------ | -------- | -------------------- |
| name      | String | Yes      | Query parameter name |

* **Returns:** `String|undefined`

```javascript
// URL: https://example.com/subscribe?gift_code=ABC123&coupon_code=SAVE20
Pelcro.helpers.getURLParameter("gift_code"); // "ABC123"
Pelcro.helpers.getURLParameter("coupon_code"); // "SAVE20"
```

### loadSDK

`Pelcro.helpers.loadSDK(src, id, options)`

Dynamically loads an external JavaScript file into the page. Skips loading if a script with the same `id` already exists.

| Parameter | Type   | Required | Description                                                        |
| --------- | ------ | -------- | ------------------------------------------------------------------ |
| src       | String | Yes      | URL of the script to load                                          |
| id        | String | Yes      | Unique ID for the script element                                   |
| options   | Object | No       | Additional script attributes (e.g. `{ async: true, defer: true }`) |

```javascript
Pelcro.helpers.loadSDK(
  "https://js.stripe.com/v3",
  "pelcro-sdk-stripe",
  { async: true }
);
```

### loadCSS

`Pelcro.helpers.loadCSS(href, id)`

Dynamically loads an external CSS stylesheet into the page. Skips loading if a link with the same `id` already exists.

| Parameter | Type   | Required | Description                    |
| --------- | ------ | -------- | ------------------------------ |
| href      | String | Yes      | URL of the stylesheet          |
| id        | String | Yes      | Unique ID for the link element |

```javascript
Pelcro.helpers.loadCSS(
  "https://js.stripe.com/v3/integrations/812.css",
  "pelcro-css-stripe"
);
```

### getOgArticleTags

`Pelcro.helpers.getOgArticleTags()`

Returns the values of all `article:tag` Open Graph meta tags on the current page. These tags are used by the paywall to determine content restriction matching.

* **Returns:** `String[]|null` - Array of tag values, or `null` if none found.

```javascript
// <meta property="article:tag" content="sports">
// <meta property="article:tag" content="football">
Pelcro.helpers.getOgArticleTags(); // ["sports", "football"]
```

### getOgEntitlements

`Pelcro.helpers.getOgEntitlements()`

Returns the values of all `pelcro:entitlements` meta tags on the current page. Used by the SDK to check content access via entitlements.

* **Returns:** `String[]|null` - Array of entitlement identifiers, or `null` if none found.

```javascript
// <meta property="pelcro:entitlements" content="premium">
// <meta property="pelcro:entitlements" content="archive">
Pelcro.helpers.getOgEntitlements(); // ["premium", "archive"]
```

### getOgUrl

`Pelcro.helpers.getOgUrl()`

Returns the value of the `og:url` Open Graph meta tag.

* **Returns:** `String|Array` - The canonical URL string, or an empty array if not found.

```javascript
// <meta property="og:url" content="https://example.com/article/123">
Pelcro.helpers.getOgUrl(); // "https://example.com/article/123"
```

### getOgArticleSection

`Pelcro.helpers.getOgArticleSection()`

Returns the value of the `article:section` Open Graph meta tag.

* **Returns:** `String|Array` - The section name, or an empty array if not found.

```javascript
// <meta property="article:section" content="Technology">
Pelcro.helpers.getOgArticleSection(); // "Technology"
```

### getMetaTagContent

`Pelcro.helpers.getMetaTagContent(name)`

Returns the content of a meta tag matching the given name.

| Parameter | Type   | Required | Description                 |
| --------- | ------ | -------- | --------------------------- |
| name      | String | Yes      | Meta tag name to search for |

* **Returns:** `String[]|null` - Content split by commas, or `null` if not found.

```javascript
// <meta name="keywords" content="news,sports,technology">
Pelcro.helpers.getMetaTagContent("keywords"); // ["news", "sports", "technology"]
```

### getHtmlLanguageAttribute

`Pelcro.helpers.getHtmlLanguageAttribute()`

Returns the language code from the page's `<html lang="">` attribute, without the region suffix.

* **Returns:** `String|null`

```javascript
// <html lang="fr-CA">
Pelcro.helpers.getHtmlLanguageAttribute(); // "fr"
```

### getScrollPercent

`Pelcro.helpers.getScrollPercent()`

Returns the current scroll position as a percentage of the total scrollable height.

* **Returns:** `Number` - Integer between 0 and 100.

```javascript
window.addEventListener("scroll", () => {
  const pct = Pelcro.helpers.getScrollPercent();
  if (pct >= 50) {
    console.log("User scrolled past 50%");
  }
});
```

***

## Authentication Token & JWT Expiry

The SDK stores the authentication token in a cookie named `pelcro.user.auth.token` with a 60-day lifetime. The cookie is refreshed automatically on every page load when the SDK detects an existing token and re-authenticates the user.

To access the token programmatically:

```javascript
const token = Pelcro.user.read().auth_token;
```

When the cookie expires (after 60 days without a page visit), the user is no longer authenticated and will need to log in again.

* The JWT (JSON Web Token) TTL is also 60 days, but it does not get extended on page reloads.

As a result, even if the cookie is extended, the JWT will expire exactly 60 days after the user first logs in, requiring them to re-authenticate.

## Customizable Membership Status Access

The JS SDK  gives you more control over who can access your gated content. You can define which membership statuses should be allowed access by using the new `Pelcro.uiSettings.membershipSubscriptionStatusAccess ` [setting](https://docs.pelcro.com/docs/react-elements#uisettings).

If you don't configure this setting, the SDK will default to the following allowed statuses:
\["active", "extended", "trialing", "past\_due"]

To customize which statuses are allowed, simply update your configuration like so:

`Pelcro.uiSettings = {
  membershipSubscriptionStatusAccess: ["active"] // Only allow active members to view content
};`

## FAQ

#### What should I do if I want to use Pelcro's SDK only without the UI?

Simply replace the UI environment property with empty whitespace.

```javascript
window.Pelcro.environment.ui = " ";
```

#### How do I deal with errors coming from calling Pelcro's SDK methods?

Requests will be validated by the API using server-side validations. Error messages returned by the API are accessible as follows:

```javascript
window.Pelcro.user.login({
    email: "useremail@example.com",
    password: "INVALID_PASSWORD",
}, (error, response) => {
    if (error) {
    	console.log("error", error.response.data.error.message); // "Invalid credentials! Please try again."
    	console.log("error", error.response.data.error.status); // 404
    }
})
```

API status for errors will be either 4xx or 5xx depending on the severity of the error. Validation errors will be 4xx while server errors will be 5xx.

# Sub pages

* [Modules](https://docs.pelcro.com/v2.4/docs/javascript-sdk-modules.md)
* [Events](https://docs.pelcro.com/v2.4/docs/javascript-sdk-events.md)

# Sibling pages

* [Model Context Protocol (MCP)](https://docs.pelcro.com/v2.4/docs/mcp.md)
* [Webhooks](https://docs.pelcro.com/v2.4/docs/webhooks.md)
* [iOS SDK](https://docs.pelcro.com/v2.4/docs/ios-sdk.md)
* [Android SDK](https://docs.pelcro.com/v2.4/docs/android-sdk.md)