TrustReviews.io

Developers · Frontend SDK

trustreviews.js

One small script to show review badges and to send and show TrustReview Events on any site. 20 badge styles, eight event types, themes, colours and CSS hooks. No framework needed.

Install

Add the script tag, then place a badge anywhere with a data-trustreviews attribute. The file is about 42 KB unminified and has no dependencies.

<script src="https://trustreviews.io/sdk/trustreviews.js" async></script>
<div data-trustreviews="card"></div>

Using a bundler? The package name will be trustreviews:

npm i trustreviews   # example: the npm package is not published yet

Or set it up in code with your public key:

<script src="https://trustreviews.io/sdk/trustreviews.js"></script>
<script>
  TrustReviews.init({
    key: "pk_live_your_public_key",   // public key, safe in the browser
    theme: "auto",                     // light | dark | auto
    locale: "en"                       // en | fr | de | es
  });
  TrustReviews.badge("#reviews-badge", { style: "card" });
  TrustReviews.events.start({ position: "bottom-left", interval: 8000, maxPerSession: 5 });
</script>

Status: public keys are not issued yet and the API answers 401, so every widget on this page runs on built-in sample data. The same code switches to your live data once your key works.

Badge gallery

Every badge below is rendered live by trustreviews.js. Copy a snippet, or change the options. All styles accept the same options: theme, size, colours, radius, font, locale, show logo and minimum stars.

Playground

Pick a style and change the settings. The snippet updates as you go.

Event types

TrustReview Events show verified customer activity as a small notice. Each type has its own wording. These are rendered with sample data.

Event simulator

Build a notice, then press Simulate event to fire a real one on this page through the SDK. Auto-play cycles random sample events every few seconds. The photos are sample images.

Event
Photo
Style

Send events

trustreviews.js can also create TrustReview Events, so showing and sending live in one file. Call TrustReviews.track() when something happens, like a purchase. It hashes the user id, queues the event, retries on failure, and resolves with the new event’s id and verify_url.

Premium: sending events uses the TrustReviews API, which is part of the Premium plan. Keys are not issued yet, so with a real key every request currently returns 401 unauthorized and track() rejects with that error. With no key it runs in demo mode and returns a sample response.

Purchase

<script src="https://trustreviews.io/sdk/trustreviews.js"></script>
<script>
  TrustReviews.init({
    key: "pk_live_your_publishable_key",  // publishable key only, never sk_
    salt: "your_site_salt"                // from your dashboard, used to hash user_id
  });

  // After checkout, once the customer ticked "show my purchase"
  TrustReviews.track("purchase", {
    event_id: "order_10482",              // your order id, also the idempotency key
    user_id: "8812",                      // hashed in the browser with SHA-256
    first_name: "Sarah", last_name: "Kent",
    item: "Pro Plan", value: 59, currency: "GBP",
    city: "London", country: "GB",
    consent: { display: true, method: "checkout_checkbox" }
  }).then((res) => {
    console.log(res.id, res.verify_url);  // evt_..., https://trustreviews.io/verify/event/...
  }).catch((err) => {
    console.warn(err.code, err.message);  // e.g. consent_required, unauthorized
  });
</script>

Booking

TrustReviews.track("booking", {
  event_id: "bk_55120",
  user_id: currentUser.id,
  first_name: "James", last_name: "Patel",
  item: "a table for two",
  city: "Manchester",
  occurred_at: "2026-11-23T19:30:00Z",
  photo_url: "https://cdn.yourshop.com/avatars/551.jpg",
  metadata: { party_size: "2" },
  consent: { display: true, timestamp: consentTime, method: "booking_form" }
}, { showToast: true });                  // also show the notice on this page

How it handles your data

  • Keys. Use a publishable key (pk_live_ or pk_test_). It can only create events. A secret key (sk_) passed in the browser is refused with a console warning.
  • User id. user_id is hashed in the browser with SHA-256 and your salt before it leaves the page. A salt in browser code is not secret: anyone can read it. For the strongest privacy, hash ids on your server and pass id_hash instead, or send the whole event from your server.
  • IP address. The SDK never collects or sends an IP. Our server masks the request IP to 123.123.123.xxx and only uses it to estimate a city when you don’t send one.
  • Consent. Pass consent: { display: true } only after the customer agreed to be shown. Without it, track() rejects with consent_required and nothing is sent.
  • Reliability. Events are queued and sent in small batches, retried with backoff on network errors, 429 and 5xx, and sent with navigator.sendBeacon if the visitor leaves the page. event_id is the idempotency key, so a retry never creates a duplicate.

Recommended: send from your server

// Recommended: send from your server with your secret key (Node 18+)
import crypto from "node:crypto";

const idHash = crypto.createHash("sha256")
  .update(process.env.TRUSTREVIEWS_SALT + String(order.userId))
  .digest("hex");

await fetch("https://trustreviews.io/api/v2/events", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.TRUSTREVIEWS_SECRET_KEY}`,  // sk_..., server only
    "Content-Type": "application/json",
    "Idempotency-Key": order.id
  },
  body: JSON.stringify({
    event_name: "purchase", event_id: order.id, occurred_at: new Date().toISOString(),
    user: { id_hash: idHash, first_name: order.firstName, last_name: order.lastName },
    item: { name: order.itemName }, location: { city: order.city },
    consent: { consent_given: true, consent_method: "checkout_checkbox" }
  })
});

// Then pass only the hash to the browser if you also call track() there:
// TrustReviews.track("purchase", { id_hash: idHash, ... })

Hooks

TrustReviews.on("queued", (e) => console.log("queued", e.idempotency_key));
TrustReviews.on("sent",   (e) => console.log("sent", e.response.verify_url));
TrustReviews.on("error",  (e) => console.warn(e.error.code, e.error.message));

Fields

FieldTypeDefaultWhat it does
eventNamestringrequiredYour event name: purchase (the main one), booking, signup or your own. Lowercase letters, numbers, underscores.
user_idstring | numberuser_id or id_hashHashed in the browser as sha256(salt + user_id). Never sent raw.
id_hashstringuser_id or id_hashA hash you made on your server. Recommended.
first_name, last_namestringrequiredOnly the first name and last initial are shown by default.
photo_urlstringoptionalSquare HTTPS image, at least 128 px.
item or descriptionstringoptionalWhat it was about, for example Pro Plan.
value, currencynumber, stringoptionalOrder value. Hidden unless show_value is true.
city, countrystringoptionalShown as “from city”. country is a 2-letter code.
consent{ display, timestamp, method }requireddisplay must be true. Events without it are refused before sending.
occurred_atISO 8601 or DatenowWhen it happened.
event_idstringrandomYour id for the event. Also the idempotency key, so retries never create duplicates.
metadataobjectoptionalUp to 20 string keys for your own use. Never shown.

Options

OptionTypeDefaultWhat it does
init: keypk_live_ | pk_test_nonePublishable key. Without a key, track() runs in demo mode and returns a sample response. Keys starting with sk_ are refused with a console warning.
init: saltstringnonePer-site salt for hashing user_id. Required when you pass user_id.
init: debugbooleanfalseLogs every request, retry and response to the console.
init: dryRunbooleanfalseBuilds and validates requests but never sends them.
init: flushIntervalms800Events sent within this window go out together as one batch.
init: maxRetriesnumber5Retries for network errors, 429 and 5xx, with exponential backoff (1s, 2s, 4s up to 30s) and Retry-After.
track opts: showToastboolean | notice optionsfalseAlso show the notice on this page once accepted.
track opts: testbooleanfalseValidate without displaying. Always on for pk_test_ keys.
track opts: dryRun, idempotencyKey, keysee abovenonePer-call overrides.

Errors reject with err.code, err.message and, for API errors, err.status. Codes include consent_required, invalid_request, invalid_event_name, salt_required, secret_key_in_browser, invalid_key, unauthorized (401), network_error and crypto_unavailable. Full field reference: POST /api/v2/events.

JavaScript API

TrustReviews.init(options)                 // set key, theme, locale; returns TrustReviews
const b = TrustReviews.badge(target, options) // render a badge; returns { el, update(), destroy() }
b.update({ theme: "dark" })
TrustReviews.events.start(options)         // cycle notices from your events feed
TrustReviews.events.show(event, options)   // show one notice now
TrustReviews.events.stop()
const off = TrustReviews.events.on("show", (e) => console.log(e.event))  // show | click | close | limit | start | stop | queued | sent | error
off()                                      // remove the listener
TrustReviews.events.track(name, data, opts) // send an event; resolves { id, verify_url }
TrustReviews.track(name, data, opts)        // same as events.track
TrustReviews.events.flush()                // send queued events now
TrustReviews.destroy()                     // remove every badge, notice and the base stylesheet

Options

Badges

OptionTypeDefaultWhat it does
keystringnonePublic key from your dashboard. Without a valid key the SDK uses sample data.
stylestringmini-starsBadge style. One of the 20 names in the gallery.
themelight | dark | autolightauto follows the visitor’s system setting.
sizesm | md | lg | numbermdBase font size. Everything scales from it.
accent, star, bg, text, borderCSS colourthemeColours. Sets the matching CSS variable on the widget.
radiusnumber | CSS length8Corner radius in px.
fontCSS font-familyinheritUses your page font by default.
localeen | fr | de | esenLanguage of labels and number format.
showLogobooleantrueShow the TrustReviews mark where the style has one.
minStars1 to 50Only show reviews with at least this rating (lists, carousels, quotes).
limitnumber3How many reviews to show in list and grid styles.
shadowbooleanfalseAdds a soft shadow.
classNamestringnoneExtra class on the widget root.

Events

OptionTypeDefaultWhat it does
positionbottom-left | bottom-right | top-left | top-rightbottom-leftCorner for notices.
designclassic | pill | dark | minimal | large | bar | nophotoclassicNotice design.
intervalms8000Time between notices.
delayms2000Wait before the first notice.
durationms5000How long each notice stays. 0 keeps it until dismissed.
maxPerSessionnumber5Stop after this many notices in a browser session.
animationslide | fade | noneslideEntrance animation. Reduced motion turns it off.
mobilebottom | same | hidebottomUnder 600px wide: full-width at the bottom, same corner, or hidden.
showVerified, showTimebooleantrueShow the verified line and the time.
accent, bg, text, radius, width, fontSize, shadowsee badgesthemeStyling, same as badges.
customCSSstringnoneCSS added inside the notice, for quick overrides.

CSS variables and hooks

Set variables on the widget or any parent. Class hooks are stable across versions.

VariableControls
--trj-bgBackground
--trj-fgText
--trj-mutedSecondary text
--trj-accentAccent, checks, buttons
--trj-starFilled star
--trj-star-emptyEmpty star
--trj-borderBorders
--trj-radiusCorner radius
--trj-fontFont family
--trj-sizeBase font size
--trj-shadowShadow
--trj-widthNotice width

Class hooks: .trj (root), .trj-badge, .trj-style-{name}, .trj-stars / .trj-star, .trj-score, .trj-box, .trj-logo, .trj-toasts[data-pos], .trj-toast[data-design], .trj-av, .trj-line, .trj-meta, .trj-x.

/* Every widget has the .trj class and reads these variables */
#reviews-badge .trj {
  --trj-bg: #ffffff;
  --trj-fg: #0c3035;
  --trj-accent: #14b8a6;
  --trj-star: #00b67a;
  --trj-radius: 4px;
  --trj-font: "Inter", system-ui, sans-serif;
}
/* Class hooks */
.trj-card .trj-score { font-size: 2.4em; }
.trj-toast .trj-line { font-weight: 500; }

Accessibility and privacy

  • Star ratings have a text label (for example “4.7 out of 5 stars”). Notices use role="status" in a polite live region, so screen readers announce them without stealing focus.
  • Every notice has a dismiss button, and carousels have labelled buttons. Nothing auto-advances.
  • Animations switch off when the visitor prefers reduced motion.
  • The SDK sets no cookies. It stores one session counter for maxPerSession in sessionStorage.
  • Event notices only show first name, last initial and city, and only for customers who agreed to be shown.

Changelog

  • 1.0.0 (November 2026): send TrustReview Events with track(): browser SHA-256 hashing of user ids, consent check, batching, retries with backoff, sendBeacon on page exit, idempotency keys, dry run and debug modes, and queued, sent and error hooks. Secret keys are refused in the browser. The verified checkmark now always sits inline before “Verified by TrustReviews”.
  • 0.9.0 (November 2026): first public preview. 20 badge styles, 8 event types, 7 notice designs, playground and simulator. Sample data until keys are issued.