AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Automating Personalized Onboarding Videos with the Elai.io REST API and Webhooks

Solène Génard · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Personalized onboarding videos dramatically accelerate product activation in B2B SaaS. Addressing a newly registered customer by their first name, displaying their company logo, and highlighting the specific workflow module they selected during signup routinely lifts trial-to-paid conversion rates by 15% to 35%. However, scaling this experience manually is impossible: a customer success team cannot hand-record, edit, and export bespoke MP4 clips for hundreds or thousands of daily registrations.

The solution is an automated, zero-touch rendering pipeline. By coupling the Elai.io REST API with asynchronous webhook callbacks, engineering teams can convert dynamic user metadata directly into tailored, AI-narrated MP4 videos within minutes.

At 365Finds, our institutional evaluation is clear: Elai.io is the premier choice for automated onboarding pipelines when your video narrative requires presentation-style structure—combining presenter avatars with dynamic typography, background product UI captures, and multi-slide layouts. While competing platforms like HeyGen or Tavus excel at pure conversational talking-head closeups, Elai.io treats video as a programmable multi-layer canvas.

This guide details the complete technical implementation: configuring dynamic template placeholders, executing variable substitution via the /api/v1/videos/renderTemplate/{videoId} endpoint, securing webhook event ingestion, handling single-attempt delivery constraints, and connecting the rendered output to downstream CRM marketing workflows.


Architecture Overview: The Asynchronous Video Pipeline

Video rendering is computationally intensive. Video synthesis—including photorealistic neural avatar lip-sync, text-to-speech (TTS) audio generation, and multi-layer WebGL canvas composition—takes between 2 to 7 minutes per minute of output. Consequently, video generation must never be invoked synchronously in the user signup request cycle.

The recommended production architecture decouples the user registration flow from video processing using an asynchronous event-driven loop.

flowchart TD
    A["New User Registration\n(Web / App Signup)"] --> B["Backend Ingestion Service\n(Extracts Name, Company, Domain)"]
    B --> C["Elai.io REST API\nPOST /videos/renderTemplate/{videoId}"]
    C -->|"HTTP 200 (Queued)\nReturns requestId"| D["Save Job State\n(Status: pending_render)"]
    
    subgraph "Elai.io Cloud Infrastructure"
        E["Rendering Engine\n- Avatar Lip Sync\n- Canvas Layer Composition\n- MP4 Encoding"]
    end
    C -.-> E
    
    E -->|"POST Webhook Event\n(video_ready)"| F["API Gateway / Webhook Ingestion\n(HMAC Signature Verification)"]
    F -->|"HTTP 200 (Ack < 10s)"| E
    F --> G["Background Queue (BullMQ / SQS)"]
    G --> H["Notification Service\n(HubSpot / Customer.io / SendGrid)"]
    H --> I["Personalized Onboarding Email / In-App Message\n(Dynamic MP4 Video & GIF Thumbnail)"]
    
    subgraph "Resilience Cron Worker"
        J["Hourly Cron Job\nGET /videos/{videoId}"] -.->|"Reconcile Missed Deliveries"| D
    end

Architectural Key Steps

  1. Trigger & Payload Construction: A new user signup event emits identity parameters (e.g., first name, workspace name, plan tier, uploaded logo URL).
  2. Asynchronous Dispatch: The backend sends a single-row batch to Elai.io's template rendering endpoint and records an internal job mapping the returned requestId and videoId to the user.
  3. Cloud Synthesis: Elai.io synthesizes speech, fits dynamic text into canvas containers, fetches remote image assets, and encodes the MP4.
  4. Push Notification: Elai.io dispatches an authenticated HTTP POST payload to your webhook receiver upon completion (video_ready) or error (video_error).
  5. Downstream Delivery: Your webhook worker updates your database and signals your marketing automation platform (e.g., Customer.io, HubSpot, Klaviyo) to trigger a personalized welcome email featuring an animated GIF thumbnail and MP4 link.
  6. Reconciliation Sweeper: A scheduled task periodically polls Elai.io to recover any dropped deliveries caused by network timeouts.

Step 1: Template Engineering in Elai.io Studio

Before making API calls, you must design a master onboarding template inside the Elai.io web application. The template establishes the visual layout, avatar positioning, transition animations, and dynamic placeholders.

1. Dynamic Text and Speech Tags

To inject user-specific copy, wrap your variable keys in double curly braces: {{tag_name}}.

2. Auto-Adjusting Typography (fitTextBox)

In real-world SaaS registrations, text lengths vary wildly—a customer's first name might be "Bo" (2 characters) or "Bartholomew" (11 characters), and company names range from short acronyms to long corporate entities.

To prevent elongated text from overflowing slide boundaries or clipping against the avatar, Elai.io provides an automated bounding-box calculation feature:

3. Dynamic Media Elements (Logos & Product UI Captures)

You can dynamically replace slide background graphics, company logos, and screenshots:

  1. Upload a placeholder image or company logo onto the slide canvas.
  2. Select the image element in Elai.io Studio.
  3. Look at the right-hand properties sidebar: once your account has an API token generated, an API Id (a unique numeric identifier, e.g., 457597335176) appears for that element.
  4. Record this ID. In your API request payload, passing this ID as a key with a publicly accessible image URL will overwrite the placeholder asset during rendering.

Step 2: Triggering Renders via the Personalization API

Elai.io handles template variable substitution and batch generation through its dedicated Personalization endpoint:

POST https://apis.elai.io/api/v1/videos/renderTemplate/{videoId}

Critical Plan & Credential Requirements

Single-User Onboarding Request Payload

To generate an onboarding video immediately after registration, construct a single-item array in templateData:

{
  "templateData": [
    {
      "first_name": "Jordan",
      "company_name": "Acme Dynamics",
      "plan_tier": "Enterprise Growth",
      "growth_goal": "Automate Onboarding",
      "457597335176": "https://cdn.example.com/customer-logos/acme-dynamics.png"
    }
  ],
  "requestId": "onboarding_usr_98412a_seq1",
  "tags": ["onboarding", "tier-enterprise", "locale-en"],
  "fitTextBox": true,
  "public": false,
  "render": true,
  "emailNotification": false
}

Field Specifications

Dispatch Implementation (Node.js / TypeScript)

import axios from 'axios';

interface OnboardingVideoRequest {
  userId: string;
  firstName: string;
  companyName: string;
  planTier: string;
  logoUrl: string;
}

interface ElaiRenderResponse {
  accepted: boolean;
  requestId: string;
  videoId?: string;
}

export async function triggerPersonalizedOnboardingVideo(
  user: OnboardingVideoRequest,
  templateId: string,
  logoElementApiId: string
): Promise<ElaiRenderResponse> {
  const elaiApiToken = process.env.ELAI_API_TOKEN;
  if (!elaiApiToken) throw new Error('ELAI_API_TOKEN is missing');

  const payload = {
    templateData: [
      {
        first_name: user.firstName,
        company_name: user.companyName,
        plan_tier: user.planTier,
        [logoElementApiId]: user.logoUrl,
      },
    ],
    requestId: `usr_${user.userId}_${Date.now()}`,
    tags: ['onboarding', user.planTier.toLowerCase().replace(/\s+/g, '-')],
    fitTextBox: true,
    public: false,
    render: true,
    emailNotification: false,
  };

  try {
    const response = await axios.post<ElaiRenderResponse>(
      `https://apis.elai.io/api/v1/videos/renderTemplate/${templateId}`,
      payload,
      {
        headers: {
          'Authorization': `Bearer ${elaiApiToken}`,
          'Content-Type': 'application/json',
        },
        timeout: 10000,
      }
    );

    // When templateData has exactly 1 item, videoId is returned immediately
    console.log(`Video render queued: Video ID ${response.data.videoId}, Request ID: ${response.data.requestId}`);
    return response.data;
  } catch (error: any) {
    if (error.response) {
      console.error(`Elai API Error: Status ${error.response.status}`, error.response.data);
      if (error.response.status === 429) {
        throw new Error(`Elai Rate Limit / Quota Exceeded: ${error.response.data.message}`);
      }
    }
    throw error;
  }
}

[!IMPORTANT] Understanding the HTTP 200 Response: An HTTP 200 OK from /videos/renderTemplate/{videoId} signifies that the job was accepted and queued, not that the video is finished. Slide validation and media asset fetching execute asynchronously. Do not poll immediately; wait for the webhook callback.


Step 3: Webhook Subscription and Cryptographic Verification

Because rendering is asynchronous, webhooks provide the only real-time push mechanism to notify your system when an MP4 is ready for distribution.

1. The Subscription Order Trap

When setting up webhooks programmatically, there is a critical dependency order:

  1. Subscribe first: Call POST https://apis.elai.io/api/v1/webhook/ with your endpoint URL and techEmail.
  2. Set secret token second: Call POST https://apis.elai.io/api/v1/webhook/secret with your shared secret string.

[!WARNING] If you call POST /webhook/secret before a webhook is actively enabled on the workspace, Elai.io silently discards the secret while still returning HTTP 200. Deliveries will then arrive unsigned, causing your signature verification to fail. Always subscribe first, set the secret second, and verify the configuration with GET /apiConfig.

2. Single-Attempt Delivery Rules

Elai.io’s webhook dispatcher enforces strict operational behavior:

3. Cryptographic Signature Verification

When a secret is configured, Elai.io signs every outbound webhook delivery with two HTTP headers:

To prevent replay attacks and ensure payload authenticity, verify the raw bytes before parsing JSON:

// Express.js Webhook Receiver Implementation
const express = require('express');
const crypto = require('crypto');

const app = express();
const WEBHOOK_SECRET = process.env.ELAI_WEBHOOK_SECRET;

// Preserve raw body buffer for byte-accurate HMAC calculation
app.use(
  express.json({
    verify: (req, _res, buf) => {
      req.rawBody = buf.toString('utf8');
    },
  })
);

function verifyElaiSignature(req) {
  const timestamp = req.headers['elai-timestamp'];
  const receivedSig = req.headers['elai-signature'];

  if (!timestamp || !receivedSig || !WEBHOOK_SECRET) {
    return false;
  }

  // Reject payloads older than 5 minutes to prevent replay attacks
  const currentTime = Date.now();
  if (Math.abs(currentTime - parseInt(timestamp, 10)) > 5 * 60 * 1000) {
    return false;
  }

  const payloadToSign = `${timestamp}.${req.rawBody}`;
  const computedSig = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(payloadToSign)
    .digest('hex');

  if (receivedSig.length !== computedSig.length) {
    return false;
  }

  return crypto.timingSafeEqual(Buffer.from(receivedSig), Buffer.from(computedSig));
}

app.post('/api/webhooks/elai', async (req, res) => {
  // 1. Authenticate request
  if (!verifyElaiSignature(req)) {
    return res.status(401).send('Invalid signature');
  }

  // 2. Acknowledge within 10 seconds to satisfy Elai.io single-attempt requirement
  res.status(200).send({ received: true });

  // 3. Hand off payload to asynchronous queue worker
  const { event, error, requestId, video } = req.body;

  try {
    if (event === 'video_ready' && video && video.status === 'ready') {
      console.log(`Video ready: ${video._id}, Request ID: ${requestId}`);
      // Push to job queue (e.g., BullMQ / SQS)
      await queueOnboardingEmailJob({
        requestId,
        videoId: video._id,
        videoUrl: video.url,
        thumbnailUrl: video.thumbnail,
        duration: video.duration,
      });
    } else if (event === 'video_error') {
      console.error(`Render failed for request ${requestId}:`, error);
      // Fallback: Notify CRM to send default static onboarding email
      await triggerFallbackOnboardingFlow(requestId, error);
    }
  } catch (err) {
    console.error('Error dispatching webhook background task:', err);
  }
});

Step 4: The Webhook Payload and Downstream CRM Integration

When a video completes rendering, Elai.io delivers a video_ready event containing direct S3 storage URLs:

{
  "event": "video_ready",
  "error": null,
  "requestId": "usr_98412a_seq1",
  "batchRowId": "0",
  "video": {
    "_id": "64bc819f72b210001a4e58b1",
    "name": "Hello Jordan!",
    "status": "ready",
    "public": false,
    "deleted": false,
    "tags": ["api", "onboarding", "tier-enterprise"],
    "userId": "61b1529d2055d2805c0",
    "accountId": "61b1529d2055d2805c",
    "duration": 42.15,
    "data": {},
    "thumbnail": "https://elai-media.s3.eu-west-2.amazonaws.com/videos/64bc819f72b210001a4e58b1/thumbnail.jpg",
    "url": "https://elai-media.s3.eu-west-2.amazonaws.com/videos/64bc819f72b210001a4e58b1/hello-jordan.mp4",
    "createdAt": "2026-11-05T01:30:00.000Z",
    "updatedAt": "2026-11-05T01:34:25.000Z"
  }
}

Passing Assets to Customer.io / HubSpot

Most email clients do not support inline MP4 video playback. To achieve optimal click-through rates:

  1. Store video.url and video.thumbnail as custom attributes on the user profile in your CRM (customer.custom_onboarding_video_url and customer.custom_onboarding_thumbnail_url).
  2. Construct an email template displaying the thumbnail image overlaid with a video play button icon.
  3. Link the image directly to your product's onboarding portal or a custom branded landing page: https://app.example.com/welcome?v=64bc819f72b210001a4e58b1.

Production Reliability & Error Recovery (Fail-Safe Sweeper)

Because network failures can interrupt single-attempt webhook deliveries, a production-grade system must implement two reliability patterns: an out-of-band reconciliation worker and fallback mechanisms for validation errors.

1. The Polling Sweeper

Run a cron job every 10 to 15 minutes that queries your database for onboarding video jobs in pending_render state older than 10 minutes. The worker reconciles missing statuses via the Video Retrieval endpoint:

GET https://apis.elai.io/api/v1/videos/{videoId}

If video.status === "ready", the sweeper dispatches the marketing event and updates the internal database record, neutralizing the risk of lost webhook events.

2. Common Rendering Errors and Workarounds

Error MessageRoot CauseEngineering Resolution
Slide N is too long. Please limit speech to Xs.Dynamic text variable generated excessive speech exceeding slide maximums.Clamp input text length at prompt generation; split long scripts across multiple slides.
Slide N uses a premium avatar that is no longer available...Master template references an avatar tier not included in current plan.Re-bind template to workspace-approved standard avatar or upgrade workspace tier.
You do not have enough minutes to render this video...Workspace minute balance depleted.Implement balance alerting via GET /users/me; purchase minute top-ups automatically.
Too many videos in one batch request, maximum is 200Exceeded batch array limit.Chunk bulk requests into batches of ≤ 200 rows.
Bare 401 UnauthorizedInvalid token OR organization is on an unsupported plan (e.g., Unlimited).Check workspace plan type under Settings; ensure token is generated by workspace admin.

Strategic Evaluation: When to Choose Elai.io for Onboarding

Evaluation DimensionElai.io REST APIHeyGen APITavus Conversational API
Primary StrengthMulti-slide presentations, dynamic typography, canvas image swappingHigh photorealism avatars, wide voice library1-on-1 dynamic camera angle talking-head clones
Template LayoutFull multi-layer canvas (avatar, text, background graphics, shapes)Pre-configured avatar scenesSingle talking head frame
Variable Injection{{tags}} in text + TTS speech + API IDs for canvas mediaDynamic avatar script variablesPhoneme/video segment stitching
Webhook ModelSingle attempt, HMAC signed (video_ready, video_error)Webhook events with automatic retriesWebhook callbacks upon completion
Rendering Latency3–8 minutes (Asynchronous)3–7 minutes (Asynchronous)1–4 minutes (Asynchronous)
Ideal Use CaseProduct onboarding tours, feature overviews, multi-metric dashboard updatesMarketing video generation, automated social clipsHigh-touch executive welcome notes

365Finds Recommendation


References