Angular Integration
Ekoo widget in an Angular application, with the transcript rendered on the server
data-ekooReqdata-ekoo-product-idReqdata-ekoo-localeautodata-ekoo-variantdata-ekoo-review-iddata-ekoo-on-eventdata-ekoo-directionnormaldata-ekoo-scale1data-ekoo-animationpulsedata-ekoo-animation-durationcontinuousdata-ekoo-always-openfalsedata-ekoo-show-imagetruedata-ekoo-not-fully-clickablefalsedata-ekoo-autoplayfalsedata-ekoo-audio-preloadmetadatadata-ekoo-show-transcriptfalsedata-ekoo-show-speed-buttonfalsedata-ekoo-closed-state-main-textdata-ekoo-closed-state-secondary-textdata-ekoo-modeautodata-shadow-modeopenwindow.EKOO_FORCE_SPA = truewindow.ekooShadowMode = "open"With Angular SSR, the product page calls Ekoo on the server: the transcript and its JSON-LD are in the initial HTML, readable without JavaScript. On hydration, the browser reuses the response fetched by the server, with no second call.
Before you start
Requirements
- Angular 20 or later with
@angular/ssr(ng new --ssrorng add @angular/ssr). Verified with Angular 22.2 and Node.js 24.15. - TypeScript.
Three values to prepare
- Website ID: in the backoffice, Settings → Organization, Organization ID field, or in the
data-ekooattribute of the widget already installed. - Product reference: exactly the one in
data-ekoo-product-idon your site and in Ekoo (ID or SKU), without changing convention. - Language: an explicit value such as
froren, the same asdata-ekoo-locale. Neverauto.
Is an A/B experiment comparing the widget with no widget running on these pages? Read the server rendering limits first.
1. Add the Ekoo functions
Copy these two files as is into src/app/lib/. They build the API address, check the response, pick the audio the way the widget does and build the JSON-LD: there is nothing to change in them.
1// Ekoo API response types23export type EkooReviewType = 'review' | 'testimony'45export interface EkooReviewUser {6 id: string7 firstname: string8 lastname: string9 image_url: string10 description: string11}1213export interface EkooReview {14 id: string15 type: EkooReviewType16 label: string17 rating: number18 audio_url: string19 is_active: boolean20 is_default: boolean21 transcript: string22 locale?: string23 created_at?: string24 user: EkooReviewUser25}2627export interface EkooExperimentVariation {28 id: string29 name: string30 widgetEnabled: boolean31 widgetConfigId: string | null32 audioSelection: string33 audioId: string | null34 audioPosition: number | null35 audioIdsByLocale?: Record<string, string>36 allocation: number37 position: number38 config?: unknown39}4041export interface EkooExperiment {42 id: string43 name: string44 variations: EkooExperimentVariation[]45}4647export interface EkooProduct {48 id: string49 external_id: string50 name?: string51 seo_name?: string52 seo_description?: string53 audio_url?: string54 website: { id: string; name?: string }55 features?: { ctaAnalytics: boolean }56 config?: Record<string, unknown>57 experiment?: EkooExperiment58 reviews: EkooReview[]59}6061export interface EkooProductList {62 limit: number63 offset: number64 count_item: number65 items: EkooProduct[]66}1// lib/ekoo.ts2import type { EkooProduct, EkooReview } from './ekoo-types'34const EKOO_ORIGIN = 'https://app.ekoo.co'56const AUDIO_FORMATS = new Map([7 ['mp3', 'audio/mpeg'],8 ['m4a', 'audio/mp4'],9 ['ogg', 'audio/ogg'],10 ['wav', 'audio/wav']11])1213export type EkooProductQuery = {14 websiteId: string15 productRef: string16 /** Same value as data-ekoo-locale. Never 'auto': the server does not know the browser language. */17 locale: string18}1920export type FetchEkooProductOptions = EkooProductQuery & {21 timeoutMs?: number22 init?: RequestInit23}2425export function buildEkooProductUrl({ websiteId, productRef, locale }: EkooProductQuery) {26 return `${EKOO_ORIGIN}/ws/websites/${encodeURIComponent(websiteId)}/products/${encodeURIComponent(productRef)}?${new URLSearchParams({ locale })}`27}2829/** 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 null33 if (!Array.isArray((body as EkooProduct).reviews)) return null34 return body as EkooProduct35}3637/** 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 init44}: 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 null52 return parseEkooProduct(await res.json())53 } catch {54 // Timeout or network error: the page renders without the Ekoo block.55 return null56 }57}5859/** 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] ?? null63 return playable.find((review) => review.is_default) ?? playable[0] ?? null64}6566// created_at is a PostgreSQL timestamp ("2026-09-04 15:56:31.998283+00"), not ISO 8601.67function toIsoDate(value?: string) {68 const match = value69 ?.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 undefined7273 const [, day, time, fraction = '', zone] = match74 const offset = /^[+-]\d{2}$/.test(zone) ? `${zone}:00` : zone75 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}7879/** 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).href86 const extension = new URL(contentUrl).pathname.split('.').pop()?.toLowerCase() ?? ''87 const author = [review.user.firstname, review.user.lastname].filter(Boolean).join(' ')8889 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 } : undefined101 }102}103104/** 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}108109/** 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}113114/** 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}2. Configure the application
Add provideHttpClient(withFetch()) next to provideClientHydration(), already there in an SSR project: it carries the Ekoo response from the server to the browser.
1// src/app/app.config.ts2import { provideHttpClient, withFetch } from '@angular/common/http'3import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core'4import { provideClientHydration } from '@angular/platform-browser'5import { provideRouter } from '@angular/router'67import { routes } from './app.routes'89export const appConfig: ApplicationConfig = {10 providers: [11 provideBrowserGlobalErrorListeners(),12 provideRouter(routes),13 // Hydration: the browser reuses the Ekoo response fetched by the server, with no second call.14 provideClientHydration(),15 provideHttpClient(withFetch())16 ]17}Render the product page on every request. The ** rule generated by Angular prerenders pages at build time, which fails for a route with a parameter.
1// src/app/app.routes.server.ts2import { RenderMode, ServerRoute } from '@angular/ssr'34export const serverRoutes: ServerRoute[] = [5 // Rendered on every request: a route with a parameter cannot be prerendered without the product list.6 { path: 'products/:ref', renderMode: RenderMode.Server },7 { path: '**', renderMode: RenderMode.Prerender }8]Caching (optional)
Angular SSR does not keep Ekoo responses from one request to the next: every render calls the API, with a 1.5 s timeout. Behind a CDN, add headers: { 'Cache-Control': 'public, max-age=0, s-maxage=900' } to the products/:ref rule to keep the page for 15 minutes. Do not do it if your server already sets this cache.
Load the widget script once, in the application’s HTML page:
1<!-- src/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>3. Wire your product page
Declare the route, then add the Ekoo call, the transcript and <ekoo-widget> to your product component. Angular strips <script> tags from templates, so the component adds the JSON-LD to the <head>. The widget only changes product together with its data, so it finds the JSON-LD in place on every navigation. A failed call, or one slower than 1.5 s, gives a page without the transcript, never an error.
1// src/app/app.routes.ts2import { Routes } from '@angular/router'34export const routes: Routes = [5 { path: 'products/:ref', loadComponent: () => import('./product-page').then((m) => m.ProductPage) }6]1// src/app/product-page.ts2import { DOCUMENT } from '@angular/common'3import { HttpClient } from '@angular/common/http'4import { Component, CUSTOM_ELEMENTS_SCHEMA, DestroyRef, effect, inject } from '@angular/core'5import { toSignal } from '@angular/core/rxjs-interop'6import { ActivatedRoute } from '@angular/router'7import { catchError, map, of, switchMap, timeout } from 'rxjs'89import {10 buildEkooAudioJsonLd,11 buildEkooProductUrl,12 parseEkooProduct,13 selectEkooReview,14 serializeJsonLd15} from './lib/ekoo'1617// Public identifier, the same as data-ekoo: not a secret.18const EKOO_WEBSITE_ID = 'YOUR_WEBSITE_ID'19// Same value as data-ekoo-locale. Never 'auto': the server does not know the browser language.20const EKOO_LOCALE = 'en'2122@Component({23 selector: 'app-product-page',24 schemas: [CUSTOM_ELEMENTS_SCHEMA],25 template: `26 <main>27 @if (view(); as view) {28 <!-- Transcript: text escaped by the framework, next to the widget and never inside it. -->29 @if (view.ekoo; as ekoo) {30 <section class="ekoo-transcript">31 <details>32 <summary>Read the transcript</summary>33 <p style="white-space: pre-line">{{ ekoo.review.transcript }}</p>34 </details>35 </section>36 }3738 <!-- The widget stays client-side: it becomes interactive once its script loads. -->39 <ekoo-widget40 [attr.data-ekoo]="websiteId"41 [attr.data-ekoo-product-id]="view.productRef"42 [attr.data-ekoo-locale]="locale"43 ></ekoo-widget>44 }45 </main>46 `47})48export class ProductPage {49 private readonly http = inject(HttpClient)50 private readonly document = inject(DOCUMENT)5152 protected readonly websiteId = EKOO_WEBSITE_ID53 protected readonly locale = EKOO_LOCALE5455 // The router reuses the component from one product to the next. The widget only changes product together with its data, so its JSON-LD is already in place.56 protected readonly view = toSignal(57 inject(ActivatedRoute).paramMap.pipe(58 map((params) => params.get('ref') ?? ''),59 switchMap((productRef) =>60 this.http61 .get<unknown>(buildEkooProductUrl({ websiteId: EKOO_WEBSITE_ID, productRef, locale: EKOO_LOCALE }))62 .pipe(63 timeout(1500),64 map((body) => {65 const product = parseEkooProduct(body)66 const review = product ? selectEkooReview(product) : null67 if (!product || !review?.transcript.trim()) return null68 return { review, jsonLd: serializeJsonLd(buildEkooAudioJsonLd(product, review)) }69 }),70 // Timeout or network error: the page renders without the Ekoo block.71 catchError(() => of(null)),72 map((ekoo) => ({ productRef, ekoo }))73 )74 )75 ),76 { initialValue: null }77 )7879 constructor() {80 effect(() => {81 const ekoo = this.view()?.ekoo82 const current = this.document.head.querySelector('script[data-ekoo-seo="server"]')83 if (!ekoo) {84 current?.remove()85 return86 }8788 // Angular strips <script> from templates: the JSON-LD goes through the document. The block rendered by the server is kept and only updated when its content changes, even if the audio is the same.89 const script = current ?? this.document.createElement('script')90 if (!current) {91 script.setAttribute('type', 'application/ld+json')92 script.setAttribute('data-ekoo-seo', 'server')93 this.document.head.appendChild(script)94 }95 script.setAttribute('data-ekoo-audio-id', ekoo.review.id)96 if (script.textContent !== ekoo.jsonLd) script.textContent = ekoo.jsonLd97 })9899 // When leaving the product page, its JSON-LD goes with it.100 inject(DestroyRef).onDestroy(() => this.document.head.querySelector('script[data-ekoo-seo="server"]')?.remove())101 }102}Check
- Transcript in the source code: view the page source (Ctrl+U), look for
data-ekoo-audio-idand a sentence of the transcript. - Playback: the player shows up and the audio starts on click.
- 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.
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.
1<!-- src/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. Use it in a component
Declare CUSTOM_ELEMENTS_SCHEMA and bind the product reference to the route: when it changes, the widget reloads the right product. If your project uses @angular/ssr, give this route a renderMode other than Prerender, as in the server rendering tab.
1// src/app/product-page.ts2import { Component, CUSTOM_ELEMENTS_SCHEMA, inject } from '@angular/core'3import { toSignal } from '@angular/core/rxjs-interop'4import { ActivatedRoute } from '@angular/router'5import { map } from 'rxjs'67@Component({8 selector: 'app-product-page',9 schemas: [CUSTOM_ELEMENTS_SCHEMA],10 template: `11 <ekoo-widget12 data-ekoo="YOUR_WEBSITE_ID"13 [attr.data-ekoo-product-id]="productRef()"14 data-ekoo-locale="fr"15 ></ekoo-widget>16 `17})18export class ProductPage {19 protected readonly productRef = toSignal(20 inject(ActivatedRoute).paramMap.pipe(map((params) => params.get('ref') ?? '')),21 { requireSync: true }22 )23}