Skip to content

Area: Developers

JavaScript SDK reference

The Releva JavaScript SDK is one script, https://releva.ai/sdk/v0/js/releva-sdk-js.min.js, that exposes a global Releva. Its job is one call per page, Releva.push(), which sends what the visitor is looking at and renders the personalized content Releva answers with. This page is the field-by-field reference for that call. For the setup end to end, read Connect your custom website.

The reference matches SDK version 0.71.0. The SDK is not version-pinned: every shop loads the current version from the same URL, within about an hour of a release. Releva.version() prints the version a page loaded.

<script>
document.addEventListener('relevaSdkLoaded', function () {
Releva.push('<yourAccessToken>', { cart: { products: [] } },
function (results) { /* content the SDK did not render itself */ },
function (error) { console.error(error); });
});
</script>
<script async type="text/javascript"
src="https://releva.ai/sdk/v0/js/releva-sdk-js.min.js"
onload="document.dispatchEvent(new Event('relevaSdkLoaded'));"></script>

<yourAccessToken> is the Access Token from Settings › Shop & Integration › General. It is public and identifies the shop; it is not the Secret Key.

Releva.push(accessToken, context, cb, errorCb, options)

Section titled “Releva.push(accessToken, context, cb, errorCb, options)”
Argument Type What it does
accessToken string Your shop’s Access Token. Becomes the path of the request, POST https://releva.ai/api/v0/push/{accessToken}.
context object What the visitor is looking at. See The context object.
cb function Called with the response once the SDK has rendered what it can render itself. Defaults to console.log. The object it receives is the response minus the blocks the SDK drew: only product blocks that have no layout or no CSS selector, and only banners with displayType: "custom". That is the hook for rendering content yourself.
errorCb function Called with an Error when the request fails. Defaults to logging the message. push never throws.
options object See Options. The whole object, minus functions, is sent to Releva together with the SDK version.

Error messages passed to errorCb:

Message Cause
[Releva 0.71.0] Server returned response status: 400, body: {"message":"..."} Releva rejected the request. The body names the problem, for example Domain with the provided access token cannot be found. or The object 'page' contains forbidden keys: 'foo'.
[Releva 0.71.0] Request error: ... The request did not reach Releva (network error, blocked by an extension, redirect).
[Releva 0.71.0] Unhandled error: ... An exception while building the request.

The request is sent as application/x-www-form-urlencoded with one field, formPayload, holding the base64-encoded JSON, so the browser makes no CORS pre-flight. In the DevTools Network tab the body is therefore not readable. Open the page with ?rlv_mode=debug to make the SDK log every request payload to the console for the rest of the tab session; in that mode Releva also serves product blocks and banners that are switched off or out of schedule.

Option Type What it does
hasConsent function Called once per push. When it returns true, the push carries profile.consent: "cookiesPolicy"; when it returns false, is missing or throws, "mandatoryCookies". It changes nothing else: the SDK still sets its cookies and sends the push either way. To track nothing before consent, do not call Releva.push() until consent is given.
serviceWorkerUrl string URL of the web push service worker on your origin, for example /service-worker.min.js. After each successful push the SDK asks for notification permission if it is still undecided, registers the worker and posts the subscription to POST /api/v0/pushSubscriptions/{accessToken}. Without this option the SDK never asks for permission.
clearRelevaElements boolean Removes everything the previous push rendered before rendering the new response. Use it in single-page applications on route changes.
prefix string Prefixes the names of the SDK’s own cookies (<prefix>_rlv_p, <prefix>_rlv_u, …), not _fbp, _fbc, _ga or _ttp. For two Releva shops on one cookie domain.
realm string Sends every request to https://<realm>.releva.ai instead of https://releva.ai. Only if Releva gave you a regional host.
disableTracking boolean Releva still answers with content but stores nothing: no profile, no events. The SDK still sets its cookies.
eventBridge boolean Must be exactly true. Reads the page-level event id a Releva Google Tag Manager tag sets in window.relevaEventId (or mints one) and sends it as eventId so Meta and TikTok can deduplicate browser-pixel and server events. Only for shops set up with that tag.

Releva validates the context strictly. Any key that is not listed here answers 400 with The object '<path>' contains forbidden keys: '<key>'., and a value of the wrong type answers 400 naming the field. The SDK adds its own fields before sending (see What the SDK adds); you only build the ones below.

The visitor’s basket, or the order on a checkout success page. Send it on every page.

Field Type Notes
products array The lines in the cart. Send [] when the cart is empty.
products[].id string The product id, identical to the id you send to the catalog API.
products[].price number Required. Unit price as a number.
products[].quantity number Required. Units in the cart, 0 or more.
products[].currency string ISO-4217. Required if you sell in more than one currency.
products[].variantId string The variant chosen, if your catalog has variants.
products[].custom object What the shopper chose, in the custom fields shape.
cartPaid boolean true on a checkout success page: the lines are the order just placed.
orderId string The order id, with cartPaid. Used to deduplicate against the order your server reports.

What is recorded: the SDK keeps a hash of the cart in a cookie and flags the push when the contents changed. Releva then diffs the cart against the last one it saw and stores Cart Created, Cart Item Added, Cart Item Removed or Cart Updated events. Sending the same cart on every page is correct and records nothing new. An empty cart from a device Releva has never seen records nothing. With cartPaid and orderId, and an email, phone number or known profile, Releva queues a paid order 90 seconds later, as a fallback behind the order your server sends.

Send it on product pages only.

Field Type Notes
id string Required when product is sent. Records a Viewed Product event.
variantId string The variant shown.
custom object The options currently selected.
Field Type Notes
token string (UUID) The page’s Token: from Personalization › Product Blocks. With a token, or with a URL Path that matches the page URL, the push resolves to a Releva page: a Viewed Page event is stored and the page’s blocks are returned. With neither, no page view and no blocks, but everything else is still tracked.
locale string ISO 639-1 page language, for example en. Also used for the events of this push.
currency string ISO-4217. Required if you sell in more than one currency.
ids array of string On listing and search pages, the product ids currently shown. Blocks in Re-Rank and Discover mode use them.
categories array of string The categories selected, for example ["women/shirts"].
query string The search text. A non-empty query records a Search event.
filter object The filter applied to a listing. See Filter syntax. A filter with a real clause also records a Search event.
tags array of string Tags for the search event.
blocks.tags array of string Return only product and banner blocks carrying at least one of these tags.
custom object Custom-field filters applied to the listing.
market string The market of the page. Product blocks show only products whose marketHandle matches it, and Search As You Type shows products with that marketHandle or with none. See Languages, currencies and markets.
url, referrer string Filled in by the SDK from location.href and document.referrer. Do not set them.

Send it when you know who the visitor is. Omit it, or send {}, for anonymous visitors: the SDK fills profile.id from its rlv_u cookie with the id Releva returned on the previous push. When your push sends profile.id, or profile.email or phoneNumber, Releva merges the anonymous history into that profile.

Field Type Notes
id string Your own id for the customer. Use the same id everywhere. Never send the string "undefined"; omit the field instead.
email string A valid email address.
phoneNumber string International format, +15555550123. Leave it out if you cannot convert reliably.
firstName, lastName string
registeredAt ISO-8601 date-time When the customer registered.
birthday ISO-8601 date
custom object Custom profile fields. Replaces all custom fields of the profile, including fields your server set through the profiles API. Prefer addCustom.
addCustom object Custom fields to set. Replaces the values of the keys it names and keeps all other keys.
location object { "lat": 42.6977, "lon": 23.3219 }, both numbers required.
consent string Set by the SDK from options.hasConsent. Do not set it.

There are no tag fields in the push. tags, addTags or removeTags in profile answer 400 with The object 'profile' contains forbidden keys. Set tags from your server with addTags and removeTags in Create or update profiles.

The profile is created or updated on the first push of a device and whenever the SDK’s hash of profile changes.

Update one custom field without touching the others:

Releva.push('<yourAccessToken>', {
cart: { products: [] },
profile: {
id: 'CUST-1001',
email: 'maria@example.com',
addCustom: {
string: [{ key: 'preferredStore', values: ['sofia-center'] }],
numeric: [{ key: 'shoeSize', values: [38] }]
}
}
}, function (results) {}, function (error) { console.error(error); });

After this push the profile has preferredStore and shoeSize with the new values. Every other custom field, for example a loyaltyTier your server sent, stays. The same push with custom instead of addCustom would leave the profile with only these two fields.

wishlist.products[] with id, optional variantId and custom. Like the cart, it is diffed against the last one Releva saw and records Wishlist Created, Item Added to Wishlist and Item Removed from Wishlist events.

company.id (string): the company the visitor is acting for. B2B shops only.

Custom events, one per item. The array must have at least one item when it is sent.

Field Type Notes
action string Required. The event name, shown as Custom Event: <action> on Data Platform › Events and available in segments and workflow triggers after the first event is stored.
products array id (required), variantId, price, currency, quantity. No custom here.
custom object Custom fields of the event. Send all three lists, string, numeric and date, even empty ones (see Troubleshooting on the integration page).
value, currency number, string A monetary value for the event. Derived from the products when omitted.
tags array of string
timestamp ISO-8601 date-time When the event happened. Defaults to now.
orderId string For events that belong to a completed order.
locale string Accepted, but replaced by page.locale.
eventId string Deduplication id passed to Meta and TikTok. Not stored.
Releva.push('<yourAccessToken>', {
cart: { products: [] },
events: [
{
action: 'compareAdd',
tags: ['compare'],
products: [{ id: 'DEMO-1001' }],
custom: {
string: [{ key: 'source', values: ['product-page'] }],
numeric: [],
date: []
}
}
]
}, function (results) {}, function (error) { console.error(error); });

The event belongs to the visitor who pushes it; there are no identifier fields on an event, and email on an event is rejected. The server-side alternative, with the secret key, is described in Events API overview.

Custom fields on products, cart lines, profiles and events all have one shape: three optional lists, each of { key, values } objects.

{
"string": [{ "key": "size", "values": ["M"] }],
"numeric": [{ "key": "weightGrams", "values": [310] }],
"date": [{ "key": "inPromoUntil", "values": ["2026-12-31"] }]
}

Keep a key in one type and one spelling everywhere: size as a string on one product and a number on another are two unrelated fields. In filters a custom field is addressed as custom.<type>.<key>, for example custom.string.size.

A filter is a group (operator plus nested) or a condition. Groups nest to any depth.

Field On Values
operator group and, or
nested group child conditions or groups
key condition a standard field such as price, or custom.<type>.<key>
operator condition eq, lt, gt, lte, gte, or a range pair gte,lte, gte,lt, gt,lte, gt,lt
value condition the value as a string; two comma-separated values for a range
action condition include, exclude, boost, bury
weight condition orders several boost or bury rules (optional)
{
"operator": "and",
"nested": [
{ "key": "price", "operator": "gte,lte", "value": "10,50", "action": "include" },
{ "key": "custom.string.size", "operator": "eq", "value": "M", "action": "include" }
]
}
You send Releva stores (label on Data Platform › Events)
a page.token, or a URL whose path matches a page’s URL Path Viewed Page
product.id Viewed Product
page.query, or a page.filter with a real clause Search
a cart whose contents changed Cart Created, Cart Item Added, Cart Item Removed or Cart Updated
cart.cartPaid with orderId and an identified visitor a paid order, 90 seconds later, unless your server reported the same orderId first
a wishlist whose contents changed Wishlist Created, Item Added to Wishlist, Item Removed from Wishlist
events[] one Custom Event: <action> per item
profile.* on a new device or with changed fields the profile is created or updated

Every stored event carries the page url, the visitor’s deviceId and sessionId, the A/B groupAssignment, the client ip, locale and, when the push resolved to a page, pageToken. Nothing is stored for a push without a device id; the SDK always sends one.

Fields the SDK fills in before sending, so you do not have to:

Field Source
deviceId rlv_p cookie, a UUID minted on the first visit
sessionId rlv_s session cookie
group rlv_g cookie, a random number 0-9999 used for A/B control groups; ?rlv_g=<n> in the URL overrides it
profile.id rlv_u cookie (the userId of the last response), unless you sent profile.email or phoneNumber, or your own profile.id
profile.consent from options.hasConsent
page.url, page.referrer location.href, document.referrer
page.token ?rlv_page_token=<token> in the URL replaces the token you passed, for testing a page
device platform: "web", first-seen date, session and view counts, SDK version
fbp, fbc, ga, gaSession, ttp read from the _fbp, _fbc, _ga, _ga_<stream> and _ttp cookies when present, so Releva’s server-side events for Meta, Google Analytics and TikTok match the browser ones. The SDK never writes these cookies.
rid, rpid, bid, cid, mid, and other rlv_* URL parameters attribution ids that Releva adds to links in product blocks, banners, emails and messages
mode ?rlv_mode=debug, kept in sessionStorage
cartChanged, wishlistChanged, profileChanged computed from content hashes kept in rlv_h_* cookies
Function What it does
Releva.version() Returns the SDK version string.
Releva.cookiesUsed() Returns the SDK’s cookies as [{ name, validDays }], with the prefix applied. It includes the Meta, Google and TikTok cookies the SDK reads. See Cookies.
Releva.getCookie(name) Reads a cookie by exact name. Handy inside hasConsent.
Releva.clearCookies() Deletes the identity, hash and leave-intent cookies. Does not delete rlv_first_seen, rlv_sessions and rlv_views.
Releva.requestSubscribe(email, firstName, lastName, phoneNumber, custom, subscriptions, cb, errorCb, addSubscriptions, birthday, attributions, tags, options) Posts a storefront sign-up to POST /api/v0/subscribe/request with the access token. Call Releva.push() first on the page; the access token and locale come from the last push. What happens next depends on Subscription Request Behavaior in Settings › Messaging: see Subscribe a customer from the browser.
Releva.checkSubscribed(email) Resolves to true or false from POST /api/v0/subscribe/check.
Releva.clearRelevaElements() Removes everything the SDK rendered. Same as the clearRelevaElements option.
Releva.setAccessToken(token), Releva.setRealm(realm) For pages that call the functions above without a prior Releva.push().
Releva.dumpState(), Releva.loadState(state) Carry the SDK’s cookies across a domain hand-off, for example to a checkout on another domain. loadState restores only the SDK’s own cookie names.
Releva.getCart() Since SDK 0.66.0. Returns a copy of the last cart a push published, as { total, currency? }, or null before any push carried a cart and after a paid cart. total is the sum of price * quantity over cart.products; currency comes from page.currency.
Releva.onCartChange(listener) Since SDK 0.66.0. Calls listener with the getCart() value on every cart a push publishes from now on, and with null after a paid cart. Returns a function that stops it.
Releva.trackPageEngagement(page) Starts a page engagement interval by hand (single-page apps that do not call push on a route change).
Releva.trackEvent(name) Not an event tracker: it feeds NPS survey triggers only. Use events[] in Releva.push() for custom events.
Releva.lookupOrder({ orderId, email }, onSuccess, onError) Since SDK 0.69.0. For an order status page built in Releva’s editor: posts the order number and the email the shopper typed to POST /api/v0/orders/status-reference/{accessToken}. onSuccess gets { reference }; open the page with ?rlv_odid=<reference>. onError gets { status, code }: code is notFound when the number and the email do not name one order, and invalid (nothing sent) when either is blank. Both values are trimmed before they are sent.
Releva.requestSubscribe(
'maria@example.com', 'Maria', 'Example', null, {}, ['newsletter'],
function (response) { /* 2xx */ },
function (error) { /* error.status, error.body */ }
);

All requests go to https://releva.ai (or https://<realm>.releva.ai) and authenticate with the access token in the path.

When Endpoint
Every Releva.push() POST /api/v0/push/{accessToken}
A rendered product block or banner becomes visible, once per block per page load POST /api/v0/impressions/{accessToken}
The visitor leaves the page or hides the tab (page engagement: scroll depth and active time, dropped when under one second or when the page did not resolve to a Releva page); banner and story interactions POST /api/v0/push/events/{accessToken}
After a push, with serviceWorkerUrl and granted permission; again when a subscribed browser’s identity changes (another shopper logs in, or a new device id) POST /api/v0/pushSubscriptions/{accessToken}
Releva.requestSubscribe(), Releva.checkSubscribed() POST /api/v0/subscribe/request, POST /api/v0/subscribe/check with authorization: Bearer <accessToken>
Typing in a search box, when Search As You Type is on for the shop POST /api/v0/searchAsYouType/{accessToken}
Answering an NPS survey POST /api/v0/nps/{token}/submissions
Releva.lookupOrder() POST /api/v0/orders/status-reference/{accessToken}, at most 10 lookups per 15 minutes per shop and IP address

Push responses have the shape { recommenders, banners, stories, push: { vapidPublicKey }, userId, gtmId, clientIp, userAgent }, plus search, nps and chatBot when those features are on. When GTM Id is set under Settings › Google, the SDK loads Google Tag Manager with that id and pushes view_item, view_cart, purchase, add_to_wishlist and one dataLayer entry per custom event.

The smallest request that proves an access token works, without a browser, is in Check the tracking snippet with curl.

Use this section to give your users detailed information about the cookies Releva uses, for example in your cookie banner. The table is for reference only and may lag behind SDK releases: for the up-to-date list, call Releva.cookiesUsed() in the browser, which returns [{ name, validDays }].

All SDK cookies are first-party on your domain, path=/, SameSite=Lax, and Secure on HTTPS pages. With options.prefix the rlv_* names get the prefix.

Cookie Lifetime Purpose
rlv_p 365 days Device id
rlv_g 365 days A/B group, 0-9999
rlv_s session Session id
rlv_u 365 days Releva’s profile id for the visitor, from the push response
rlv_h_profile, rlv_h_cart, rlv_h_wish, rlv_h_fbp, rlv_h_fbc, rlv_h_ga, rlv_h_ttp 365 days Content hashes for change detection
rlv_first_seen, rlv_sessions, rlv_views 365 days First visit date, session and page view counts (device statistics, NPS eligibility)
rlv_li, rlv_lib session Leave-intent campaigns already shown in this session
_fbp, _fbc, _ga, _ttp owned by Meta, Google and TikTok Read only, never written

Releva.cookiesUsed() returns the cookies in this table, including _fbp, _fbc, _ga and _ttp with validDays: 365, even though the SDK only reads those four. options.prefix never applies to them. Two more cookies are not in the list:

  • rlv_mrgd_u, 7 days, set by the SDK when a logged-in push merges an anonymous history into the profile.
  • deviceIdV2, one year, set by the Releva API on releva.ai (a third-party cookie from your site’s point of view, SameSite=None) for device linking.

The SDK also uses sessionStorage (rlv_mode, rlv_hashes, rlv_first_session) and localStorage: rlv_push_identity once the browser has a web push subscription for your shop, and, on shops where Releva has turned on bot detection or device fingerprinting, keys such as rlv_bot and rlv_f_id.

API

  • Consent API overview

    The consent and subscription calls of the Releva API, one page each - subscribe from your server or the browser, double opt-in, unsubscribe, unsubscribe links and one-click, and consent history.

  • Push notifications API overview

    How a browser or mobile app registers for Releva push notifications: the web SDK setup, the two registration endpoints, authentication with the access token, errors and limits.

  • Search as you type API overview

    Authentication, request, response, errors and limits of POST /api/v0/searchAsYouType, plus the browser SDK functions for rendering results yourself.

  • Surveys and NPS API

    The three public endpoints behind Releva's hosted survey page and the NPS widget, the nps object in the page push, the SDK functions, limits and every error message, with a working request for each.