React Integration

Ekoo widget in a React application, with the transcript rendered by Next.js

The widget auto-loads its config from the backoffice. Appearance attributes are optional overrides — no need to set them if the backoffice is configured.
Core attributes
data-ekooReq
string
Your Ekoo website UUID: backoffice, Settings → Organization, Organization ID field.
data-ekoo-product-idReq
string
Product reference (must match exactly what is in your Ekoo catalog).
data-ekoo-locale
string·default: auto
Locale code: fr, en, es, it, de, ar, cn, tw, hk, jp, kr, nl, tr, pl, pt, lu, be, ru. "auto" = navigator.language detection.
data-ekoo-variant
string
Stable reference of a widget configuration. The product, its audios, and its reviewers still come from data-ekoo-product-id; only the widget styling changes.
data-ekoo-review-id
string
ID of a specific audio review. If omitted: the product's default audio, otherwise the first published audio.
data-ekoo-on-event
string (fn name)
Name of a global window function called on each widget event (printed, played-0, played-25…).
Appearance — backoffice overrides
data-ekoo-direction
normal | reverse·default: normal
Expansion direction. normal = left-to-right, reverse = right-to-left.
data-ekoo-scale
number·default: 1
Scale factor (e.g. "1.2" for 20% larger).
data-ekoo-animation
string·default: pulse
Animation type for the widget icon at rest.
data-ekoo-animation-duration
string·default: continuous
Animation duration.
data-ekoo-always-open
boolean·default: false
If "true", the widget stays permanently expanded.
data-ekoo-show-image
boolean·default: true
Show or hide the product image in the widget.
data-ekoo-not-fully-clickable
boolean·default: false
If "true", only the play button is clickable.
data-ekoo-autoplay
boolean·default: false
Automatically start audio playback on load.
data-ekoo-audio-preload
metadata | none·default: metadata
Standalone 4.0.0: overrides the backoffice setting. “none” waits until the first click to load the file and disables autoplay.
data-ekoo-show-transcript
boolean·default: false
Show a button to read the audio transcript.
data-ekoo-show-speed-button
boolean·default: false
Show a playback speed control.
data-ekoo-closed-state-main-text
string
Main CTA text shown when the widget is collapsed.
data-ekoo-closed-state-secondary-text
string
Secondary text below the CTA when the widget is collapsed.
SPA & Shadow DOM
data-ekoo-mode
spa | static·default: auto
Forces rendering mode. Auto-detected (Next.js, Nuxt, React, Vue, Angular, Sapper). Only use if auto-detection fails.
data-shadow-mode
open | closed·default: open
"open" (default) enables inspection, external CSS access and analytics tracking. Set to "closed" to fully isolate the widget.
Global JS config
window.EKOO_FORCE_SPA = true
Forces SPA mode globally (alternative to data-ekoo-mode="spa" on each widget).
window.ekooShadowMode = "open"
Global Shadow DOM mode (alternative to data-shadow-mode on each widget).

With Next.js (App Router), the audio transcript and its JSON-LD are in the initial HTML: crawlers that do not run JavaScript can read them, and the widget stays interactive in the browser.

Before you start

Requirements

  • Next.js 15 or later, with the App Router and the Node.js runtime. Verified with Next.js 16.4.2 and React 19.2.
  • cacheComponents disabled, the default. If it is enabled, adapt the example to 'use cache' and <Suspense>.
  • TypeScript, with the @/ alias set up by create-next-app. If your project has a src/ folder, put lib/ there like app/.

Three values to prepare

  1. Website ID: in the backoffice, Settings → Organization, Organization ID field, or in the data-ekoo attribute of the widget already installed.
  2. Product reference: exactly the one in data-ekoo-product-id on your site and in Ekoo (ID or SKU), without changing convention.
  3. Language: an explicit value such as fr or en, the same as data-ekoo-locale. Never auto.

Is an A/B experiment comparing the widget with no widget running on these pages? Read the server rendering limits first.

1. Declare the ekoo-widget element

Add this file at the project root so that TypeScript accepts <ekoo-widget> in your components.

ekoo-widget.d.ts
typescript
1// ekoo-widget.d.ts
2import type { DetailedHTMLProps, HTMLAttributes } from 'react'
3
4declare module 'react' {
5 namespace JSX {
6 interface IntrinsicElements {
7 'ekoo-widget': DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
8 }
9 }
10}

2. Add the Ekoo functions

Copy these two files as is into lib/. They fetch the product, pick the audio the way the widget does and build the JSON-LD: nothing to change in them.

lib/ekoo-types.ts
typescript
1// Ekoo API response types
2
3export type EkooReviewType = 'review' | 'testimony'
4
5export interface EkooReviewUser {
6 id: string
7 firstname: string
8 lastname: string
9 image_url: string
10 description: string
11}
12
13export interface EkooReview {
14 id: string
15 type: EkooReviewType
16 label: string
17 rating: number
18 audio_url: string
19 is_active: boolean
20 is_default: boolean
21 transcript: string
22 locale?: string
23 created_at?: string
24 user: EkooReviewUser
25}
26
27export interface EkooExperimentVariation {
28 id: string
29 name: string
30 widgetEnabled: boolean
31 widgetConfigId: string | null
32 audioSelection: string
33 audioId: string | null
34 audioPosition: number | null
35 audioIdsByLocale?: Record<string, string>
36 allocation: number
37 position: number
38 config?: unknown
39}
40
41export interface EkooExperiment {
42 id: string
43 name: string
44 variations: EkooExperimentVariation[]
45}
46
47export interface EkooProduct {
48 id: string
49 external_id: string
50 name?: string
51 seo_name?: string
52 seo_description?: string
53 audio_url?: string
54 website: { id: string; name?: string }
55 features?: { ctaAnalytics: boolean }
56 config?: Record<string, unknown>
57 experiment?: EkooExperiment
58 reviews: EkooReview[]
59}
60
61export interface EkooProductList {
62 limit: number
63 offset: number
64 count_item: number
65 items: EkooProduct[]
66}
lib/ekoo.ts
typescript
1// lib/ekoo.ts
2import type { EkooProduct, EkooReview } from './ekoo-types'
3
4const EKOO_ORIGIN = 'https://app.ekoo.co'
5
6const AUDIO_FORMATS = new Map([
7 ['mp3', 'audio/mpeg'],
8 ['m4a', 'audio/mp4'],
9 ['ogg', 'audio/ogg'],
10 ['wav', 'audio/wav']
11])
12
13export type EkooProductQuery = {
14 websiteId: string
15 productRef: string
16 /** Same value as data-ekoo-locale. Never 'auto': the server does not know the browser language. */
17 locale: string
18}
19
20export type FetchEkooProductOptions = EkooProductQuery & {
21 timeoutMs?: number
22 init?: RequestInit
23}
24
25export function buildEkooProductUrl({ websiteId, productRef, locale }: EkooProductQuery) {
26 return `${EKOO_ORIGIN}/ws/websites/${encodeURIComponent(websiteId)}/products/${encodeURIComponent(productRef)}?${new URLSearchParams({ locale })}`
27}
28
29/** Keeps a valid product only, or returns null. */
30export function parseEkooProduct(body: unknown): EkooProduct | null {
31 // An unknown product answers 200 with { type, message }: test the body, not the status.
32 if (!body || typeof body !== 'object' || 'type' in body) return null
33 if (!Array.isArray((body as EkooProduct).reviews)) return null
34 return body as EkooProduct
35}
36
37/** Returns the product, or null when Ekoo has nothing to render (unknown product, error, timeout). */
38export async function fetchEkooProduct({
39 websiteId,
40 productRef,
41 locale,
42 timeoutMs = 1500,
43 init
44}: FetchEkooProductOptions): Promise<EkooProduct | null> {
45 try {
46 const res = await fetch(buildEkooProductUrl({ websiteId, productRef, locale }), {
47 ...init,
48 headers: { Accept: 'application/json' },
49 signal: AbortSignal.timeout(timeoutMs)
50 })
51 if (!res.ok) return null
52 return parseEkooProduct(await res.json())
53 } catch {
54 // Timeout or network error: the page renders without the Ekoo block.
55 return null
56 }
57}
58
59/** Same choice as the widget: unknown explicit ID → first playable audio; no ID → default audio, then first playable. */
60export function selectEkooReview(product: EkooProduct, reviewId?: string): EkooReview | null {
61 const playable = product.reviews.filter((review) => review.audio_url && review.is_active)
62 if (reviewId) return playable.find((review) => review.id === reviewId) ?? playable[0] ?? null
63 return playable.find((review) => review.is_default) ?? playable[0] ?? null
64}
65
66// created_at is a PostgreSQL timestamp ("2026-09-04 15:56:31.998283+00"), not ISO 8601.
67function toIsoDate(value?: string) {
68 const match = value
69 ?.trim()
70 .match(/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})(?:\.(\d{1,6}))?(Z|[+-]\d{2}(?::?\d{2})?)$/i)
71 if (!match) return undefined
72
73 const [, day, time, fraction = '', zone] = match
74 const offset = /^[+-]\d{2}$/.test(zone) ? `${zone}:00` : zone
75 const date = new Date(`${day}T${time}.${fraction.slice(0, 3).padEnd(3, '0')}${offset}`)
76 return Number.isNaN(date.getTime()) ? undefined : date.toISOString()
77}
78
79/** AudioObject JSON-LD: data-ekoo-audio-id tells the widget not to add a second one. */
80export function buildEkooAudioJsonLd(
81 product: EkooProduct,
82 review: EkooReview,
83 { productJsonLdId }: { productJsonLdId?: string } = {}
84) {
85 const contentUrl = new URL(review.audio_url, EKOO_ORIGIN).href
86 const extension = new URL(contentUrl).pathname.split('.').pop()?.toLowerCase() ?? ''
87 const author = [review.user.firstname, review.user.lastname].filter(Boolean).join(' ')
88
89 return {
90 '@context': 'https://schema.org',
91 '@type': 'AudioObject',
92 name: product.seo_name || product.name || undefined,
93 description: product.seo_description || undefined,
94 contentUrl,
95 encodingFormat: AUDIO_FORMATS.get(extension),
96 inLanguage: review.locale || undefined,
97 transcript: review.transcript.replace(/\r\n?/g, '\n'),
98 uploadDate: toIsoDate(review.created_at),
99 about: productJsonLdId ? { '@id': productJsonLdId } : undefined,
100 author: author ? { '@type': 'Person', name: author } : undefined
101 }
102}
103
104/** JSON.stringify does not escape "<": a transcript containing "</script>" would close the tag. */
105export function serializeJsonLd(data: object) {
106 return JSON.stringify(data).replace(/</g, '\\u003c')
107}
108
109/** Escapes text for HTML, as content or as an attribute value. */
110export function escapeHtml(text: string) {
111 return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`)
112}
113
114/** Complete JSON-LD <script> tag, for templates that insert raw HTML. */
115export function buildEkooJsonLdScriptTag(
116 product: EkooProduct,
117 review: EkooReview,
118 options: { productJsonLdId?: string } = {}
119) {
120 const data = serializeJsonLd(buildEkooAudioJsonLd(product, review, options))
121 return `<script type="application/ld+json" data-ekoo-seo="server" data-ekoo-audio-id="${escapeHtml(review.id)}">${data}</script>`
122}

3. Wire up your product page

In your existing product page, add three things: the fetchEkooProduct call with your three values, the JSON-LD and transcript block, then <ekoo-widget> right next to it. The example shows a complete page on the app/products/[ref] route; if yours differs, take only these three parts. A failed Ekoo call, or one slower than 1.5 s, gives a page without the transcript, never an error.

app/products/[ref]/page.tsx
tsx
1// app/products/[ref]/page.tsx (Next.js App Router, Server Component)
2import Script from 'next/script'
3
4import { buildEkooAudioJsonLd, fetchEkooProduct, selectEkooReview, serializeJsonLd } from '@/lib/ekoo'
5
6// Public identifier, the same as data-ekoo: not a secret.
7const EKOO_WEBSITE_ID = 'YOUR_WEBSITE_ID'
8// Same value as data-ekoo-locale. Never 'auto': the server does not know the browser language.
9const EKOO_LOCALE = 'en'
10
11export default async function ProductPage({ params }: { params: Promise<{ ref: string }> }) {
12 const { ref } = await params
13 const product = await fetchEkooProduct({
14 websiteId: EKOO_WEBSITE_ID,
15 productRef: ref,
16 locale: EKOO_LOCALE,
17 // Ekoo data cache: revalidation on demand after 900 s. Does not configure the page HTML cache.
18 init: { next: { revalidate: 900 } }
19 })
20 const review = product ? selectEkooReview(product) : null
21
22 return (
23 <main>
24 {/* Your product page */}
25
26 {product && review?.transcript.trim() ? (
27 <>
28 {/* AudioObject JSON-LD: data-ekoo-audio-id tells the widget not to add a second one. */}
29 <script
30 type="application/ld+json"
31 data-ekoo-seo="server"
32 data-ekoo-audio-id={review.id}
33 dangerouslySetInnerHTML={{ __html: serializeJsonLd(buildEkooAudioJsonLd(product, review)) }}
34 />
35 {/* Transcript: text escaped by the framework, next to the widget and never inside it. */}
36 <section className="ekoo-transcript">
37 <details>
38 <summary>Read the transcript</summary>
39 <p style={{ whiteSpace: 'pre-line' }}>{review.transcript}</p>
40 </details>
41 </section>
42 </>
43 ) : null}
44
45 {/* The widget stays client-side: it becomes interactive once its script loads. */}
46 <ekoo-widget
47 data-ekoo={EKOO_WEBSITE_ID}
48 data-ekoo-product-id={ref}
49 data-ekoo-locale={EKOO_LOCALE}
50 />
51 <Script src="https://app.ekoo.co/widgets/widget-4.0.0-standalone.js" strategy="afterInteractive" />
52 </main>
53 )
54}
ℹ️

Caching

next: { revalidate: 900 } caches the Ekoo response, not the HTML: the page is still rendered on every request, with this data revalidated in the background once the 900 s have passed. This cache also keeps an error response, such as a product not yet known to Ekoo, until it is revalidated. Test the behavior with next build then next start, not with the development server. See the Next.js caching documentation.

Check

  1. Transcript in the source code: view the page source (Ctrl+U), look for data-ekoo-audio-id and a sentence of the transcript.
  2. Playback: the player shows up and the audio starts on click.
  3. Product change: move to another product without reloading the page; the transcript and the audio played must be the new product’s.

Detailed checks, including no duplicate JSON-LD: SSR, SEO & GEO guide.

For a React application rendered only in the browser (Vite, Create React App), or to keep your current integration, show the widget only. The transcript is then readable only once JavaScript has run.

1. Load the script

Add the widget script once, in the application’s HTML page.

index.html
html
1<!-- index.html -->
2<head>
3 <!-- Widget script, loaded once for the whole site. -->
4 <script src="https://app.ekoo.co/widgets/widget-4.0.0-standalone.js" defer></script>
5</head>

2. Declare the ekoo-widget element

The same file as in the Next.js tab lets TypeScript accept <ekoo-widget>. Put it in a folder covered by your tsconfig.json, for example src/.

src/ekoo-widget.d.ts
typescript
1// ekoo-widget.d.ts
2import type { DetailedHTMLProps, HTMLAttributes } from 'react'
3
4declare module 'react' {
5 namespace JSX {
6 interface IntrinsicElements {
7 'ekoo-widget': DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>
8 }
9 }
10}

3. Show the widget

In your product page, render <ekoo-widget> and bind data-ekoo-product-id to the route. When the reference changes, React updates the attribute and the widget loads the new product; when the page unmounts, the widget goes with it.

src/pages/ProductPage.tsx
tsx
1// src/pages/ProductPage.tsx
2import { useParams } from 'react-router' // react-router-dom with React Router 6
3
4export function ProductPage() {
5 // Route /products/:ref: the product reference known to Ekoo
6 const { ref = '' } = useParams()
7
8 return (
9 <main>
10 {/* A new reference reloads the widget: nothing else to call */}
11 <ekoo-widget
12 data-ekoo="YOUR_WEBSITE_ID"
13 data-ekoo-product-id={ref}
14 data-ekoo-locale="fr"
15 />
16 </main>
17 )
18}

Go Further