Svelte / SvelteKit Integration
Ekoo widget in a Svelte application, with the transcript rendered by SvelteKit
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 SvelteKit, the load function runs on the server: the transcript and its JSON-LD are in the initial HTML, readable without JavaScript. On navigation, SvelteKit updates the attributes of <ekoo-widget> and the widget reloads the right product.
Before you start
Requirements
- SvelteKit 2, with Svelte 4 or 5. With Svelte 5, keep this page in legacy mode: it uses
export let. - 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/lib/: 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. Load the data on the server
The load function calls Ekoo with your three values and only returns what the page displays, because SvelteKit serializes this data into the HTML. If your product page already has a +page.server.ts, add these lines to it rather than replacing it.
1// src/routes/products/[ref]/+page.server.ts2import type { PageServerLoad } from './$types'34import { buildEkooJsonLdScriptTag, fetchEkooProduct, selectEkooReview } from '$lib/ekoo'56// 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'1011export const load: PageServerLoad = async ({ params }) => {12 const product = await fetchEkooProduct({13 websiteId: EKOO_WEBSITE_ID,14 productRef: params.ref,15 locale: EKOO_LOCALE16 })17 const review = product ? selectEkooReview(product) : null1819 // Only return what the page displays: SvelteKit serializes this data into the HTML.20 return {21 websiteId: EKOO_WEBSITE_ID,22 locale: EKOO_LOCALE,23 productRef: params.ref,24 ekoo:25 product && review?.transcript.trim()26 ? { transcript: review.transcript, jsonLdTag: buildEkooJsonLdScriptTag(product, review) }27 : null28 }29}Caching (optional)
The example keeps your site’s cache policy. If these pages have none, you can add setHeaders({ 'cache-control': 'public, max-age=0, s-maxage=900' }) to the load function, effective only behind a CDN or adapter that honours this header. Do not do it if your layout already sets cache-control: SvelteKit refuses to set it twice and the page returns a 500 error.
3. Display the transcript and the widget
In your existing +page.svelte, add the <svelte:head> block, the transcript and <ekoo-widget> where the player goes.
1<!-- src/routes/products/[ref]/+page.svelte -->2<script lang="ts">3 import type { PageData } from './$types'45 export let data: PageData6</script>78<svelte:head>9 <!-- AudioObject JSON-LD: data-ekoo-audio-id tells the widget not to add a second one. -->10 {#if data.ekoo}11 {@html data.ekoo.jsonLdTag}12 {/if}13</svelte:head>1415<!-- Your product page -->1617{#if data.ekoo}18 <!-- Transcript: text escaped by the framework, next to the widget and never inside it. -->19 <section class="ekoo-transcript">20 <details>21 <summary>Read the transcript</summary>22 <p style="white-space: pre-line">{data.ekoo.transcript}</p>23 </details>24 </section>25{/if}2627<!-- The widget stays client-side: it becomes interactive once its script loads. -->28<ekoo-widget29 data-ekoo={data.websiteId}30 data-ekoo-product-id={data.productRef}31 data-ekoo-locale={data.locale}32></ekoo-widget>4. Load the widget script
The template below is complete. In an existing project, keep your metadata, customizations and both SvelteKit placeholders; only add the Ekoo script once.
1<!-- src/app.html -->2<!doctype html>3<html lang="en">4 <head>5 <meta charset="utf-8" />6 <meta name="viewport" content="width=device-width, initial-scale=1" />7 %sveltekit.head%8 <!-- Widget script, loaded once for the whole site. -->9 <script src="https://app.ekoo.co/widgets/widget-4.0.0-standalone.js" defer></script>10 </head>11 <body data-sveltekit-preload-data="hover">12 <div style="display: contents">%sveltekit.body%</div>13 </body>14</html>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.
For a Svelte app without SvelteKit, or to keep your current integration, show the widget only. The transcript is then only readable once JavaScript has run.
1. Load the script
Add the widget script once, in index.html with Svelte and Vite, or in src/app.html with SvelteKit.
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. Show the widget
Render <ekoo-widget> in the product page and pass it the product reference, for example <ProductAudio productRef={data.product.ref} />. When the reference changes, including on a SvelteKit navigation that reuses the page, Svelte updates the attribute and the widget loads the new product.
1<!-- src/lib/components/ProductAudio.svelte -->2<script lang="ts">3 // The product reference known to Ekoo, from your route or your data4 export let productRef: string5</script>67<!-- A new reference reloads the widget: nothing else to call -->8<ekoo-widget9 data-ekoo="YOUR_WEBSITE_ID"10 data-ekoo-product-id={productRef}11 data-ekoo-locale="fr"12></ekoo-widget>