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 yetOr 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.
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 pageHow it handles your data
- Keys. Use a publishable key (
pk_live_orpk_test_). It can only create events. A secret key (sk_) passed in the browser is refused with a console warning. - User id.
user_idis 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 passid_hashinstead, 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.xxxand 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 withconsent_requiredand 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.sendBeaconif the visitor leaves the page.event_idis 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
| Field | Type | Default | What it does |
|---|---|---|---|
eventName | string | required | Your event name: purchase (the main one), booking, signup or your own. Lowercase letters, numbers, underscores. |
user_id | string | number | user_id or id_hash | Hashed in the browser as sha256(salt + user_id). Never sent raw. |
id_hash | string | user_id or id_hash | A hash you made on your server. Recommended. |
first_name, last_name | string | required | Only the first name and last initial are shown by default. |
photo_url | string | optional | Square HTTPS image, at least 128 px. |
item or description | string | optional | What it was about, for example Pro Plan. |
value, currency | number, string | optional | Order value. Hidden unless show_value is true. |
city, country | string | optional | Shown as “from city”. country is a 2-letter code. |
consent | { display, timestamp, method } | required | display must be true. Events without it are refused before sending. |
occurred_at | ISO 8601 or Date | now | When it happened. |
event_id | string | random | Your id for the event. Also the idempotency key, so retries never create duplicates. |
metadata | object | optional | Up to 20 string keys for your own use. Never shown. |
Options
| Option | Type | Default | What it does |
|---|---|---|---|
init: key | pk_live_ | pk_test_ | none | Publishable 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: salt | string | none | Per-site salt for hashing user_id. Required when you pass user_id. |
init: debug | boolean | false | Logs every request, retry and response to the console. |
init: dryRun | boolean | false | Builds and validates requests but never sends them. |
init: flushInterval | ms | 800 | Events sent within this window go out together as one batch. |
init: maxRetries | number | 5 | Retries for network errors, 429 and 5xx, with exponential backoff (1s, 2s, 4s up to 30s) and Retry-After. |
track opts: showToast | boolean | notice options | false | Also show the notice on this page once accepted. |
track opts: test | boolean | false | Validate without displaying. Always on for pk_test_ keys. |
track opts: dryRun, idempotencyKey, key | see above | none | Per-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 stylesheetOptions
Badges
| Option | Type | Default | What it does |
|---|---|---|---|
key | string | none | Public key from your dashboard. Without a valid key the SDK uses sample data. |
style | string | mini-stars | Badge style. One of the 20 names in the gallery. |
theme | light | dark | auto | light | auto follows the visitor’s system setting. |
size | sm | md | lg | number | md | Base font size. Everything scales from it. |
accent, star, bg, text, border | CSS colour | theme | Colours. Sets the matching CSS variable on the widget. |
radius | number | CSS length | 8 | Corner radius in px. |
font | CSS font-family | inherit | Uses your page font by default. |
locale | en | fr | de | es | en | Language of labels and number format. |
showLogo | boolean | true | Show the TrustReviews mark where the style has one. |
minStars | 1 to 5 | 0 | Only show reviews with at least this rating (lists, carousels, quotes). |
limit | number | 3 | How many reviews to show in list and grid styles. |
shadow | boolean | false | Adds a soft shadow. |
className | string | none | Extra class on the widget root. |
Events
| Option | Type | Default | What it does |
|---|---|---|---|
position | bottom-left | bottom-right | top-left | top-right | bottom-left | Corner for notices. |
design | classic | pill | dark | minimal | large | bar | nophoto | classic | Notice design. |
interval | ms | 8000 | Time between notices. |
delay | ms | 2000 | Wait before the first notice. |
duration | ms | 5000 | How long each notice stays. 0 keeps it until dismissed. |
maxPerSession | number | 5 | Stop after this many notices in a browser session. |
animation | slide | fade | none | slide | Entrance animation. Reduced motion turns it off. |
mobile | bottom | same | hide | bottom | Under 600px wide: full-width at the bottom, same corner, or hidden. |
showVerified, showTime | boolean | true | Show the verified line and the time. |
accent, bg, text, radius, width, fontSize, shadow | see badges | theme | Styling, same as badges. |
customCSS | string | none | CSS 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.
| Variable | Controls |
|---|---|
--trj-bg | Background |
--trj-fg | Text |
--trj-muted | Secondary text |
--trj-accent | Accent, checks, buttons |
--trj-star | Filled star |
--trj-star-empty | Empty star |
--trj-border | Borders |
--trj-radius | Corner radius |
--trj-font | Font family |
--trj-size | Base font size |
--trj-shadow | Shadow |
--trj-width | Notice 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
maxPerSessionin 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, andqueued,sentanderrorhooks. 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.