Dev.to WebDev 🛠 Dev 👁 0 📖 6 min read

How to Integrate Voice AI with Shopify Stores

Why Voice AI Matters for Shopify If you’ve ever browsed a store and thought, “I wish I could just ask the site to read product details out loud,” you’re not alone. Voice assistants are moving from novelty to necessity,

Why Voice AI Matters for Shopify

If you’ve ever browsed a store and thought, “I wish I could just ask the site to read product details out loud,” you’re not alone. Voice assistants are moving from novelty to necessity, and shoppers expect a more natural, hands‑free experience. Adding voice AI to a Shopify store can:

  • Boost accessibility – meet WCAG standards and serve users with visual impairments.
  • Increase engagement – people spend more time listening than reading, especially on mobile.
  • Drive conversions – a spoken product description can convey tone, excitement, and trust better than plain text.

In this post we’ll walk through a practical way to integrate text‑to‑speech (TTS) and voice cloning into a Shopify storefront, using ElevenLabs as the engine for high‑quality, realistic speech. By the end, you’ll have a working prototype that can read product titles, descriptions, and even custom messages to your customers.

Overview of the Architecture

Shopify Store
   │
   ├─ Front‑end (Liquid + JavaScript)
   │       ↓
   │   Fetch product data via Storefront API
   │       ↓
   │   Send text to ElevenLabs TTS endpoint
   │       ↓
   │   Receive audio URL → Play with HTML5 <audio>
   │
   └─ Optional backend (Node/Python) for caching & voice cloning
  • Shopify Storefront API – lets us pull product data without a full admin token.
  • ElevenLabs TTS API – generates natural‑sounding speech in seconds.
  • Caching layer (optional) – store the generated MP3s in a CDN or S3 bucket so you don’t hit rate limits.

Getting an ElevenLabs API Key

  1. Sign up at the ElevenLabs affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp
  2. Navigate to API → Keys and copy your secret key.
  3. Keep it safe – you’ll need it in the request header xi-api-key.

Step 1 – Pull Product Data from Shopify

We’ll use the Storefront GraphQL endpoint because it works directly from the browser and respects the same origin policy when you enable CORS in your Shopify admin.

// utils/shopify.js
const SHOP_DOMAIN = 'your-store.myshopify.com';
const STOREFRONT_TOKEN = 'YOUR_STOREFRONT_ACCESS_TOKEN';

export async function fetchProduct(productId) {
  const query = `
    query ($id: ID!) {
      node(id: $id) {
        ... on Product {
          title
          descriptionHtml
          media(first: 5) {
            edges {
              node {
                previewImage {
                  url
                }
              }
            }
          }
        }
      }
    }`;

  const response = await fetch(`https://${SHOP_DOMAIN}/api/2024-07/graphql.json`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': STOREFRONT_TOKEN,
    },
    body: JSON.stringify({ query, variables: { id: productId } })
  });

  const { data } = await response.json();
  return data.node;
}

Tip: Store the productId as a data-product-id attribute on your product page so the script can fetch it dynamically.

Step 2 – Generate Speech with ElevenLabs

ElevenLabs offers a simple REST endpoint that accepts plain text and returns an audio file (MP3 or WAV). Below is a curl example, followed by a JavaScript wrapper.

Curl Example

curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/EXAMPLE_VOICE_ID" \
  -H "Content-Type: application/json" \
  -H "xi-api-key: YOUR_ELEVENLABS_API_KEY" \
  -d '{
        "text": "Introducing the new Summer Breeze Dress, crafted from 100% organic cotton.",
        "model_id": "eleven_multilingual_v2",
        "voice_settings": {
          "stability": 0.75,
          "similarity_boost": 0.85
        }
      }' \
  --output summer-breeze.mp3

JavaScript Wrapper

// utils/tts.js
export async function synthesizeSpeech(text, voiceId = 'EXAMPLE_VOICE_ID') {
  const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'xi-api-key': 'YOUR_ELEVENLABS_API_KEY',
    },
    body: JSON.stringify({
      text,
      model_id: 'eleven_multilingual_v2',
      voice_settings: {
        stability: 0.75,
        similarity_boost: 0.85,
      },
    })
  });

  if (!response.ok) {
    const err = await response.text();
    throw new Error(`ElevenLabs error: ${err}`);
  }

  // The API returns raw audio bytes; we turn them into a Blob URL
  const audioBlob = await response.blob();
  return URL.createObjectURL(audioBlob);
}

Why ElevenLabs? The platform’s neural models produce lifelike prosody, and the voice cloning feature lets you create a brand‑specific voice from a few minutes of recorded speech. You can sign up through the affiliate link and get a free quota to experiment: https://try.elevenlabs.io/kr07zfuqn1bp

Step 3 – Wire It Up on the Product Page

Now we combine the two helpers. When a visitor clicks a “Listen” button, we fetch the product description, send it to ElevenLabs, and play the result.

<!-- product.liquid -->
<div id="product-info" data-product-id="{{ product.id | graphql_id }}">
  <h1>{{ product.title }}</h1>
  <button id="listen-btn">🔊 Listen</button>
</div>

<audio id="tts-player" hidden></audio>

<script type="module">
import { fetchProduct } from '/assets/utils/shopify.js';
import { synthesizeSpeech } from '/assets/utils/tts.js';

const btn = document.getElementById('listen-btn');
const audioEl = document.getElementById('tts-player');
const productId = document.getElementById('product-info').dataset.productId;

btn.addEventListener('click', async () => {
  btn.disabled = true;
  btn.textContent = 'Processing…';

  try {
    const product = await fetchProduct(productId);
    const text = `${product.title}. ${product.descriptionHtml.replace(/<[^>]+>/g, '')}`;
    const audioUrl = await synthesizeSpeech(text);
    audioEl.src = audioUrl;
    audioEl.hidden = false;
    audioEl.play();
  } catch (e) {
    console.error(e);
    alert('Sorry, something went wrong with the voice preview.');
  } finally {
    btn.disabled = false;
    btn.textContent = '🔊 Listen';
  }
});
</script>

What’s happening?

  1. Fetch product – we grab the title and stripped HTML description.
  2. Call ElevenLabs – the synthesizeSpeech function returns a temporary Blob URL.
  3. Play – the native <audio> element handles playback, pause, and volume.

Optional: Caching Audio Files

Repeatedly hitting the ElevenLabs API for the same product can waste credits. A lightweight Node.js server can store generated MP3s in an S3 bucket and serve a permanent URL.

// server/cache.js (Express + AWS SDK)
const express = require('express');
const fetch = require('node-fetch');
const { S3Client, PutObjectCommand, GetObjectCommand } = require('@aws-sdk/client-s3');
const router = express.Router();

const s3 = new S3Client({ region: 'us-east-1' });
const BUCKET = 'my-shopify-tts-cache';

router.get('/tts/:voiceId/:hash', async (req, res) => {
  const { voiceId, hash } = req.params;
  const key = `${voiceId}/${hash}.mp3`;

  // Check if file exists
  try {
    await s3.send(new GetObjectCommand({ Bucket: BUCKET, Key: key }));
    const url = `https://${BUCKET}.s3.amazonaws.com/${key}`;
    return res.redirect(url);
  } catch {
    // Not cached – generate on the fly
    const text = Buffer.from(hash, 'base64').toString('utf8');
    const apiRes = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'xi-api-key': process.env.ELEVENLABS_KEY,
      },
      body: JSON.stringify({ text, model_id: 'eleven_multilingual_v2' })
    });
    const audio = await apiRes.buffer();

    // Store in S3
    await s3.send(new PutObjectCommand({
      Bucket: BUCKET,
      Key: key,
      Body: audio,
      ContentType: 'audio/mpeg',
      ACL: 'public-read',
    }));

    const url = `https://${BUCKET}.s3.amazonaws.com/${key}`;
    res.redirect(url);
  }
});

module.exports = router;

You can now point the front‑end to /tts/:voiceId/:hash where hash is a base64‑encoded version of the product description. This pattern reduces latency after the first request and keeps your ElevenLabs usage under control.

Voice Cloning for Brand Consistency

ElevenLabs lets you upload a few minutes of your own voice (or a professional voice‑over) and generate a custom voice model. The workflow is:

  1. Record 5‑10 short sentences (≈ 1 minute total).
  2. Upload via the ElevenLabs dashboard → Voice Cloning.
  3. Receive a voice_id you can use in the TTS calls.
// Using a cloned voice
const myBrandVoiceId = 'YOUR_CLONED_VOICE_ID';
const audioUrl = await synthesizeSpeech(text, myBrandVoiceId);

The result feels like the store is speaking your brand, not a generic AI. It’s perfect for welcome greetings, checkout confirmations, or product‑specific ads.

Testing Locally

# 1️⃣ Install dependencies
npm install express node-fetch @aws-sdk/client-s3

# 2️⃣ Run the cache server
node server/cache.js

# 3️⃣ Open your Shopify theme preview and click “Listen”

If you see the audio playing without a noticeable delay, you’ve successfully wired voice AI into your store!

Going Further

  • Multi‑language support – ElevenLabs models support dozens of languages; just pass the appropriate model_id.
  • Dynamic prompts – combine cart totals, discount codes, or user names into the spoken text for a personalized experience.
  • Voice‑activated navigation – use the Web Speech API to let users say “Next product” and fetch the next item via the Storefront API.

Wrap‑up

Integrating voice AI into a Shopify store isn’t a sci‑fi fantasy—it’s a handful of API calls and a sprinkle of JavaScript. By leveraging ElevenLabs for high‑quality TTS and optional voice cloning, you can give your shoppers a richer, more accessible experience that sets your brand apart.

Ready to make your store talk? Grab your ElevenLabs API key through the affiliate link, spin up the code snippets above, and start testing. Your customers (and your conversion metrics) will thank you.

Try ElevenLabs today: https://try.elevenlabs.io/kr07zfuqn1bp 🚀

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.