does livekit provide frontend functionalities in j...
# ask-ai
s
does livekit provide frontend functionalities in javascript only ?
t
Thanks for reaching out, Vaishnavi. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're not limited to JavaScript. LiveKit provides client SDKs and UI components for multiple frontend platforms: • Web: JavaScript/TypeScript (Web SDK) and React components (
@livekit/components-react
) • React Native: JavaScript/TypeScript • iOS/macOS/visionOS: Swift (
client-sdk-swift
, SwiftUI components) • Android: Kotlin (SDK + Jetpack Compose components) • Flutter: Dart (cross-platform mobile) • Unity: C# (including WebGL builds) If you tell me which platform or framework you plan to use, I can point you to the specific SDK and next steps. Sources: Client SDKs | livekit/livekit_composite | DeepWiki | client-sdk-unity-web | livekit/livekit_composite | DeepWiki | LiveKit SDKs Overview | LiveKit Docs
s
i only want to use jaavscript not any framework like react and next.js
t
Yes — you can use LiveKit with plain JavaScript (no frameworks required). The Web SDK works in vanilla JS/TypeScript: you can connect to rooms, publish/subscribe tracks, and handle data channels directly without React or Next.js. If you'd like, tell me whether you're building a plain browser app or a build setup (Webpack/Vite), and I can give a minimal code snippet to get you started.
s
if i dont want use vite and webpack then???
t
You can run LiveKit in a plain browser with no frameworks and no bundler. Use the browser-ready Web SDK build via a script tag and minimal JS to connect, publish, and subscribe. Here’s a minimal example using CDN script tags and plain JavaScript (no Vite/Webpack/React): 1) Include the Web SDK and adapter (via unpkg):
Copy code
<script src="https://unpkg.com/@livekit/client/dist/livekit-client.umd.js"></script>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
2) Minimal HTML + JS to join a room and publish the camera:
Copy code
<button id="join">Join</button>
<video id="local" autoplay playsinline muted></video>
<div id="remote"></div>

<script>
  const { connect, LocalVideoTrack } = livekitClient;

  async function join() {
    // Fetch a token from your server (replace with your token endpoint)
    const resp = await fetch('/token'); // server must return a valid LiveKit token
    const { token } = await resp.json();

    const url = 'wss://your-livekit-host'; // replace with your LiveKit server URL
    const room = await connect(url, token);

    // publish local camera
    const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
    const track = new LocalVideoTrack(stream.getVideoTracks()[0]);
    await room.localParticipant.publishTrack(track);

    // show local video
    document.getElementById('local').srcObject = new MediaStream([stream.getVideoTracks()[0]]);

    // render remote participants
    room.on('participantConnected', p => {
      p.on('trackSubscribed', (track, publication, participant) => {
        if (track.kind === 'video') {
          const el = document.createElement('video');
          el.autoplay = true; el.playsInline = true;
          el.srcObject = new MediaStream([track.mediaStreamTrack]);
          document.getElementById('remote').appendChild(el);
        }
      });
    });
  }

  document.getElementById('join').onclick = join;
</script>
Notes and tips: • You still need a server endpoint to mint LiveKit tokens (can't create tokens securely in the browser). • Replace the token endpoint and LiveKit
wss://
URL with your own. • The UMD build exposes
livekitClient
global; check console autocomplete for available classes and helpers. • If you prefer modules without a bundler, use a CDN ESM build and
<script type="module">
(unpkg supports
?module
), but the UMD approach above works in plain HTML. Want a minimal ESM example or a ready-to-copy token endpoint snippet (Node/Express)?
s
[LiveKitManager] LiveKit SDK not found or missing connect method! [LiveKitManager] Error connecting to LiveKit: Error: LiveKit SDK not loaded. Make sure the LiveKit UMD CDN script is loaded before this script. at LiveKitManager.initialize ( ) at startInterviewFlow ( ) [LiveKitManager] Error: Failed to connect: LiveKit SDK not loaded. Make sure the LiveKit UMD CDN script is loaded before this script. ❌ INTERVIEW FLOW FAILED: Error: LiveKit SDK not loaded. Make sure the LiveKit UMD CDN script is loaded before this script. at LiveKitManager.initialize ( ) at startInterviewFlow ( ) 🔴 ERROR: Interview Error: LiveKit SDK not loaded. Make sure the LiveKit UMD CDN script is loaded before this script. Fetch finished loading: POST "
t
You're seeing that error because your code runs before the LiveKit UMD script is available. Let's fix it — checklist and quick fixes: 1. Ensure the UMD script is included before your script:
Copy code
<script src="https://unpkg.com/@livekit/client/dist/livekit-client.umd.js"></script>
<script src="your-script.js"></script>
1. If both scripts are in the same HTML file, move your code below the UMD script or wrap it so it runs after load:
Copy code
<script src="https://unpkg.com/@livekit/client/dist/livekit-client.umd.js"></script>
<script>
  window.addEventListener('load', () => {
    // safe to use livekitClient.connect() here
  });
</script>
1. If you dynamically load the UMD script, wait for it to finish:
Copy code
const s = document.createElement('script');
s.src = 'https://unpkg.com/@livekit/client/dist/livekit-client.umd.js';
s.onload = () => { /* initialize LiveKit here */ };
document.head.appendChild(s);
1. Verify the global exists before using it:
Copy code
if (!window.livekitClient || !window.livekitClient.connect) {
  console.error('LiveKit SDK not loaded');
} else {
  const { connect } = window.livekitClient;
  // proceed
}
1. Check browser console/network: • Confirm the UMD script loads (200 OK). • Look for CSP or mixed-content errors blocking the script. • Ensure no adblocker/extension is blocking unpkg. If you want, share your HTML (the script tag order) or the exact snippet where you call
connect()
and I’ll point out the exact line to change.
s
index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>1-to-1 Interview Platform</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Font Awesome CDN --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" /> <!-- Yur CSS file (place inside: assets/css/style.css) --> <link rel="stylesheet" href="../assets/styles.css" /> </head> <body> </div> <!-- External Libraries & SDKs --> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4"></script> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-cpu@4"></script> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-webgl@4"></script> <!-- LiveKit SDK - LOADED ONLY ONCE, BEFORE YOUR SCRIPTS --> <script src="https://cdn.jsdelivr.net/npm/livekit-client/dist/livekit-client.min.js"></script> <script> // Global config window.CONFIG = { LIVEKIT_URL: "wss://videochat-rk8nnpx3.livekit.cloud", ANALYTICS_POLLING_INTERVAL: 10000, OBJECT_DETECTION_INTERVAL: 2000 }; // Debug: Verify LiveKit SDK is loaded console.log('📦 [Page Load] LiveKit SDK loaded'); console.log(' window.LivekitClient:', typeof window.LivekitClient); </script> <!-- Your JS scripts - LOADED AFTER LiveKit SDK --> <script src="../assets/js/api.js"></script> <script src="../assets/js/analytics.js"></script> <script src="../assets/js/audio.js"></script> <script src="../assets/js/ui.js"></script> <script src="../assets/js/ws.js"></script> <script src="../assets/js/object_detection.js"></script> <script src="../assets/js/demo.js"></script> <script src="../assets/js/init.js"></script> <script src="../assets/js/bundle.js"></script> <script src="../assets/js/app.js"></script> </body></html> interview_join.html <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Join Interview</title> <!-- Load LiveKit SDK FIRST (ONLY ONCE) --><script src="https://cdn.jsdelivr.net/npm/livekit-client/dist/livekit-client.min.js"></script> <!-- Then load CSS --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"> </head> <body> <div class="container-wrapper"> <div class="card"> <div class="card-header"> <h2>Interview Portal</h2> </div> <div class="card-body"> <!-- Loading State --> <div id="loadingState" class="status-message status-loading"><span class="spinner"></span> Processing your request... </div><!-- Success State --><div id="successState" class="hidden"><div class="status-message status-success<strong>Ready to join!</strong></div> <div class="info-section"> <p><strong>Candidate:</strong> <span id="candidateName">-</span></p> <p><strong>Session:</strong> <span id="sessionID">-</span></p><p><strong>Interviewer:</strong> <span id="selectedInterviewer">-</span></p><p><strong>Interview Type:</strong> <span id="interviewType">-</span></p></div> <div id="interviewerSelector" class="interviewer-selector hidden"> <h4>Select Your Interviewer</h4><p style="font-size: 13px; color: #666; margin-bottom: 12px;">Multiple interviewers are available for this session. Please select one to proceed.</p><div id="interviewerList" class="interviewer-list"></div></div><div class="btn-group-vertical"><button id="joinBtn" class="btn btn-primary"> Join Interview Now </button><button id="retryBtn" class="btn btn-secondary" onclick="location.reload()"> Start Over</button></div></div> <!-- Error State --> <div id="errorState" class="hidden"> <div class="status-message status-error"> <strong>Failed to Process Request</strong> </div> <p id="errorMessage" style="color: #C62828; font-size: 14px; text-align: center; margin: 16px 0;"> An error occurred. Please try again. </p> <div class="btn-group-vertical"> <button class="btn btn-secondary" onclick="location.reload()"> Try Again</button></div></div></div></div</div><script> class InterviewJoinFlow { constructor() { const urlParams = new URLSearchParams(window.location.search); this.room = urlParams.get('room'); this.token = urlParams.get('token'); this.identity = urlParams.get('identity'); this.randomID = this.room ? null : this.extractRandomIDFromURL(); this.sessionData = null; this.selectedInterviewer = null; this.loadingState = document.getElementById('loadingState'); this.successState = document.getElementById('successState'); this.errorState = document.getElementById('errorState'); this.joinBtn = document.getElementById('joinBtn'); this.interviewerSelector = document.getElementById('interviewerSelector'); this.interviewerList = document.getElementById('interviewerList'); this.initializeFlow(); } extractRandomIDFromURL() { const pathParts = window.location.pathname.split('/').filter(p => p); return pathParts.length > 0 ? pathParts[pathParts.length - 1] : null;} async initializeFlow() { if (this.room && this.token && this.identity) { this.showSuccess(); setTimeout(() => this.joinInterview(), 1000); return;} if (!this.randomID) { this.showError('Invalid interview link.'); return; } try{ await this.fetchSessionData(); this.showSuccess(); if (this.sessionData.action === 'SELECT_INTERVIEWER') { this.showInterviewerSelector(); } } catch (error) { this.showError(error.message || 'Failed to process request'); } } async fetchSessionData() { const response = await fetch(
/api/port/${encodeURIComponent(this.randomID)}/
, { method: 'GET', headers: { 'Content-Type': 'application/json' } }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error || 'Backend error'); } this.sessionData = await response.json(); if (this.sessionData.token) { sessionStorage.setItem('livekit_token', this.sessionData.token); } } showSuccess() { this.loadingState.classList.add('hidden'); this.successState.classList.remove('hidden'); const data = this.sessionData || {}; document.getElementById('candidateName').textContent = data.candidate_name || this.identity || 'User'; document.getElementById('sessionID').textContent = data.sessionID || this.room || 'N/A'; document.getElementById('selectedInterviewer').textContent = data.selected_interviewer || 'TBD'; document.getElementById('interviewType').textContent = data.interview_type || 'manual'; this.joinBtn.addEventListener('click', () => this.joinInterview()); } showInterviewerSelector() { const interviewers = this.sessionData.interviewers || []; if (interviewers.length === 0) return; this.interviewerSelector.classList.remove('hidden'); this.interviewerList.innerHTML = ''; interviewers.forEach((interviewer, index) => { const btn = document.createElement('button'); btn.className = 'interviewer-btn'; btn.textContent = interviewer; btn.onclick = () => this.selectInterviewer(btn, interviewer); if (index === 0) { btn.classList.add('selected'); this.selectedInterviewer = interviewer; } this.interviewerList.appendChild(btn); }); this.joinBtn.textContent = 'Confirm Selection'; this.joinBtn.onclick = () => this.confirmInterviewerAndJoin(); } selectInterviewer(btn, interviewerName) { document.querySelectorAll('.interviewer-btn').forEach(b => b.classList.remove('selected')); btn.classList.add('selected'); this.selectedInterviewer = interviewerName; } async confirmInterviewerAndJoin() { if (!this.selectedInterviewer) { this.showError('Please select an interviewer'); return; } const response = await fetch('/api/select-interviewer/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ random_id: this.randomID, sessionID: this.sessionData.sessionID, selected_interviewer: this.selectedInterviewer, candidate_name: this.sessionData.candidate_name, candidate_id: this.sessionData.candidate_id, interview_type: this.sessionData.interview_type, }), }); if (!response.ok) { const errorData = await response.json(); this.showError(errorData.error || 'Failed to confirm interviewer'); return; } const newData = await response.json(); this.sessionData = newData; if (newData.token) { sessionStorage.setItem('livekit_token', newData.token); } document.getElementById('selectedInterviewer').textContent = this.selectedInterviewer; this.interviewerSelector.classList.add('hidden'); this.joinBtn.textContent = 'Join Interview Now'; this.joinBtn.onclick = () => this.joinInterview(); } joinInterview() { const token = this.token || this.sessionData?.token; const room = this.room || this.sessionData?.sessionID; const identity = this.identity || this.sessionData?.candidate_name || 'User'; const interviewer = this.sessionData?.selected_interviewer || ''; if (!token || !room) { this.showError('No token or room provided!'); return; } const indexURL = new URL('index.html', window.location.origin + window.location.pathname.replace(/[^/]*$/, '')); indexURL.searchParams.set('room', room); indexURL.searchParams.set('token', token); indexURL.searchParams.set('identity', identity); indexURL.searchParams.set('interviewer', interviewer); window.location.href = indexURL.toString(); } showerror(message) { this.loadingState.classList.add('hidden'); this.successState.classList.add('hidden'); this.errorState.classList.remove('hidden'); document.getElementById('errorMessage').textContent = message; } } document.addEventListener('DOMContentLoaded', () => { new InterviewJoinFlow(); }); </script> </body> </html>
t
Thanks — I reviewed your HTML. The SDK error happens because the page is checking for the LiveKit global before it's available or using the wrong global name. Quick fixes tailored to your files: 1) Use the correct UMD global: the LiveKit UMD exposes
livekitClient
(lowercase L), not
LivekitClient
or
window.LivekitClient
. Update your debug check:
Copy code
console.log('window.livekitClient:', typeof window.livekitClient);
2) Ensure scripts run after the SDK load: • Keep the SDK <script> tag before your scripts (you already do), and make initialization run on DOM load or SDK load. Example (place in the inline script after the SDK tag or in your app.js init):
Copy code
window.addEventListener('load', () => {
  if (!window.livekitClient || !window.livekitClient.connect) {
    console.error('LiveKit SDK not loaded');
    return;
  }
  // safe to call livekitClient.connect() here
});
Or, if dynamically loading, use
s.onload = () => { /* init */ }
. 3) Fix any naming mismatches in your code: • Search your JS for
LivekitClient
,
LiveKitClient
, or other variants and replace with
livekitClient
. • Also check any checks like
if (!window.livekitClient.connect)
— test existence as
if (!window.livekitClient || !window.livekitClient.connect)
. 4) Verify network/CSP/blocking: • Open DevTools → Network: confirm the SDK file (livekit-client.min.js) returns 200. • Check Console for mixed-content, CSP, or extension blocking errors. 5) Small HTML note: some of your HTML has minor typos (missing closing tags, escaped underscores). Those won't cause the SDK error but clean them up to avoid other issues. If you want, paste the small snippet from where you call
connect()
(in app.js or init.js) and I’ll point exactly where to add the load check or rename the global.
s
i have done changes stille rror [LiveKitManager] Available globals with "live": Array(0) init.js:80 [LiveKitManager] LiveKit SDK not found or missing connect method! initialize @ init.js:80Understand this error init.js:111 [LiveKitManager] Error connecting to LiveKit: Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. at LiveKitManager.initialize (init.js8115) at startInterviewFlow (init.js3026) initialize @ init.js:111Understand this error init.js:277 [LiveKitManager] Error: Failed to connect: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. showError @ init.js:277Understand this error init.js:37 ❌ INTERVIEW FLOW FAILED: Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. at LiveKitManager.initialize (init.js8115) at startInterviewFlow (init.js3026) startInterviewFlow @ init.js:37Understand this error init.js:384 🔴 ERROR: Interview Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script.
t
Thanks — I can see the error persists. You're getting "LiveKit SDK not loaded" because your code still can't find a usable LiveKit global before calling initialize/connect. Let's narrow this down. What I'll need from you • Paste the top ~120 lines of init.js (the file that logs the errors and calls LiveKit). That will let me point to the exact line causing the early call or wrong global check. Quick checks to run now (try these and tell me results) 1) Verify global name and presence in console • Open DevTools → Console and paste: console.log(Object.keys(window).filter(k => k.toLowerCase().includes('live'))); • Share the output. If it’s empty, the SDK isn’t loading into window. 2) Confirm the SDK script actually loaded (Network) • In DevTools → Network, reload and search for livekit-client.min.js. Is its status 200? Any CSP/mixed-content errors in Console? 3) Add a safe runtime check before initializing (temporary change in init.js) • Wrap initialization so it waits for the SDK:
Copy code
function waitForLivekit(timeout = 5000) {
  const start = Date.now();
  return new Promise((resolve, reject) => {
    (function check() {
      if (window.livekitClient && typeof window.livekitClient.connect === 'function') return resolve();
      if (Date.now() - start > timeout) return reject(new Error('LiveKit SDK not loaded'));
      setTimeout(check, 50);
    })();
  });
}

window.addEventListener('load', async () => {
  try {
    await waitForLivekit();
    // call your LiveKit initialization here
  } catch (e) {
    console.error('LiveKit not available:', e);
  }
});
• Add this temporarily and reload; report whether the "LiveKit not available" error appears or whether initialization proceeds. 4) Confirm script order and duplicates • Ensure only one SDK script tag exists across pages. Multiple or wrong CDN paths may expose different globals. From your HTML you use cdn.jsdelivr.net — that's fine if the file returns 200. 5) Check for blocking (adblock/CSP/extensions) • Try in an incognito window with extensions disabled. If you paste the init.js snippet I asked for, I’ll point to the exact fix (rename, reorder, or where to add the wait).
s
init.js async function startInterviewFlow() { console.log('='.repeat(50)); console.log('🚀 STARTING INTERVIEW FLOW'); console.log('='.repeat(50)); try { // Step 1: Extract encryptedId from URL and fetch interview data console.log('\n📍 STEP 1: Fetching interview data from backend...'); const interviewData = await initializeInterview(); console.log('✅ Interview data received:', interviewData); // Step 3: Credentials are already stored by initializeInterview() const credentials = getStoredCredentials(); console.log('\n📍 STEP 3: Credentials stored in sessionStorage'); console.log('✅ Room:', credentials.room); console.log('✅ Identity:', credentials.identity); console.log('✅ Candidate:', credentials.candidateName); // Step 4: Auto-join LiveKit meeting with credentials console.log('\n📍 STEP 4: Auto-joining LiveKit meeting...'); const livekitManager = new LiveKitManager(); await livekitManager.initialize(credentials.room, credentials.token, credentials.identity); console.log('\n' + '='.repeat(50)); console.log('✅ INTERVIEW FLOW COMPLETE - MEETING STARTED!'); console.log('='.repeat(50)); } catch (error) { console.error('❌ INTERVIEW FLOW FAILED:', error); showError(
Interview Error: ${error.message}
); } } // Auto-start interview flow when page loads document.addEventListener('DOMContentLoaded', () => { console.log('📄 Page loaded, starting interview flow...'); startInterviewFlow(); }); class LiveKitManager { constructor() { this.room = null; this.token = null; this.identity = null; this.liveKitUrl = window.CONFIG?.LIVEKIT_URL || 'wss://videochat-rk8nnpx3.livekit.cloud'; } /** * Initialize LiveKit connection with room credentials */ async initialize(room, token, identity) { console.log('[LiveKitManager] Initializing with room:', room); console.log('[LiveKitManager] Identity:', identity); console.log('[LiveKitManager] LiveKit URL:', this.liveKitUrl); this.room = room; this.token = token; this.identity = identity; try { // Check if LiveKit SDK is loaded (correct global is window.livekitClient - lowercase) console.log('[LiveKitManager] Checking for LiveKit SDK...'); // The correct UMD global is window.livekitClient (lowercase L) const livekitClient = window.livekitClient; console.log('[LiveKitManager] window.livekitClient available:', !!livekitClient); console.log('[LiveKitManager] Available globals with "live":', Object.keys(window).filter(k => k.toLowerCase().includes('live'))); if (!livekitClient || !livekitClient.connect) { console.error('[LiveKitManager] LiveKit SDK not found or missing connect method!'); throw new Error('LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script.'); } console.log('[LiveKitManager] ✅ LiveKit SDK found and ready'); console.log('[LiveKitManager] Connecting to LiveKit...'); // Connect to LiveKit const room_obj = await livekitClient.connect(this.liveKitUrl, token, { autoSubscribe: true, audio: true, video: true, publishDefaults: { codec: 'vp9', maxBitrate: 2_500_000 } }); console.log('[LiveKitManager] ✅ Connected to LiveKit!'); console.log('[LiveKitManager] Room:', room_obj.name); console.log('[LiveKitManager] Local Participant:', room_obj.localParticipant.name); this.setupVideoElements(room_obj); this.setupEventListeners(room_obj); // Store room reference for later use window.liveKitRoom = room_obj; return room_obj; } catch (error) { console.error('[LiveKitManager] Error connecting to LiveKit:', error); this.showError('Failed to connect: ' + error.message); throw error; } } /** * Setup video elements for local and remote participants */ setupVideoElements(room) { console.log('[LiveKitManager] Setting up video elements...'); // Find or create video container let videoContainer = document.getElementById('video-container'); if (!videoContainer) { videoContainer = document.querySelector('.video-section'); } if (!videoContainer) { console.warn('[LiveKitManager] Video container not found - creating one'); videoContainer = document.createElement('div'); videoContainer.id = 'video-container'; videoContainer.style.cssText = ` display: grid; grid-template-columns: 1fr 1fr; gap: 10px; width: 100%; height: 100%; padding: 10px;
Copy code
;
      document.body.appendChild(videoContainer);
    }

    // Setup local participant video
    if (room.localParticipant) {
      console.log('[LiveKitManager] Setting up local video');
      const localContainer = document.createElement('div');
      localContainer.id = 'local-participant';
      localContainer.style.cssText =
background: #000; border-radius: 8px; overflow: hidden; position: relative;
Copy code
;

      // Create video element
      const videoElement = document.createElement('video');
      videoElement.autoplay = true;
      videoElement.muted = true;
      videoElement.style.cssText =
width: 100%; height: 100%; object-fit: cover; `; // Attach local video tracks room.localParticipant.videoTrackPublications.forEach(trackPub => { if (trackPub.videoTrack) { trackPub.videoTrack.attach(videoElement); console.log('[LiveKitManager] Local video attached'); } }); localContainer.appendChild(videoElement); videoContainer.appendChild(localContainer); } // Setup remote participants room.participants.forEach((participant) => { this.setupRemoteParticipant(videoContainer, participant, room); }); // Listen for new remote participants room.on('participantConnected', (participant) => { console.log('[LiveKitManager] Remote participant connected:', participant.identity); this.setupRemoteParticipant(videoContainer, participant, room); }); } /** * Setup a remote participant's video */ setupRemoteParticipant(container, participant, room) { const participantContainer = document.createElement('div'); participantContainer.id = `participant-${participant.sid}`; participantContainer.style.cssText = ` background: #000; border-radius: 8px; overflow: hidden; position: relative;
Copy code
;

    const videoElement = document.createElement('video');
    videoElement.autoplay = true;
    videoElement.style.cssText =
width: 100%; height: 100%; object-fit: cover;
Copy code
;

    // Add participant name overlay
    const nameLabel = document.createElement('div');
    nameLabel.textContent = participant.name || participant.identity;
    nameLabel.style.cssText =
position: absolute; bottom: 10px; left: 10px; background: rgba(0,0,0,0.7); color: white; padding: 5px 10px; border-radius: 4px; font-size: 12px;
Copy code
;

    participantContainer.appendChild(videoElement);
    participantContainer.appendChild(nameLabel);
    container.appendChild(participantContainer);

    // Attach video tracks when subscribed
    participant.videoTrackPublications.forEach(trackPub => {
      if (trackPub.videoTrack) {
        trackPub.videoTrack.attach(videoElement);
        console.log('[LiveKitManager] Remote video attached:', participant.identity);
      }
    });

    // Listen for new track subscriptions
    participant.on('trackSubscribed', (track) => {
      if (track.kind === 'video') {
        track.attach(videoElement);
        console.log('[LiveKitManager] Video track subscribed:', participant.identity);
      }
    });

    // Cleanup when participant disconnects
    room.on('participantDisconnected', (p) => {
      if (p.sid === participant.sid) {
        participantContainer.remove();
        console.log('[LiveKitManager] Participant removed:', participant.identity);
      }
    });
  }

  /**
   * Setup room event listeners
   */
  setupEventListeners(room) {
    room.on('disconnected', () => {
      console.log('[LiveKitManager] Disconnected from room');
      this.showError('Disconnected from interview');
    });

    room.on('participantDisconnected', (participant) => {
      console.log('[LiveKitManager] Participant disconnected:', participant.identity);
    });

    room.on('error', (error) => {
      console.error('[LiveKitManager] Room error:', error);
      this.showError('Interview error: ' + error.message);
    });
  }

  /**
   * Show error message
   */
  showError(message) {
    console.error('[LiveKitManager] Error:', message);
    const errorDiv = document.createElement('div');
    errorDiv.style.cssText =
position: fixed; top: 20px; right: 20px; background: #F8D7DA; color: #721C24; padding: 15px 20px; border-radius: 4px; border: 1px solid #F5C6CB; max-width: 400px; z-index: 10000; font-family: Arial, sans-serif; box-shadow: 0 2px 10px rgba(0,0,0,0.2);
Copy code
;
    errorDiv.innerHTML =
<strong>⚠️ Error:</strong> ${message} <button onclick="this.parentElement.remove()" style=" background: none; border: none; color: #721C24; cursor: pointer; margin-left: 10px; font-weight: bold; ">&times;</button> `; document.body.appendChild(errorDiv); // Auto-remove after 5 seconds setTimeout(() => { if (errorDiv.parentElement) { errorDiv.remove(); } }, 5000); } }
t
Thanks — you’ve given the exact init flow and logs, which is helpful. The error means your code still can’t find the UMD global
livekitClient
when initialize() runs. Let’s verify and fix with the smallest, targeted checks. 1) Quick console checks (paste results) • Run these in DevTools Console and share outputs: ◦ Object.keys(window).filter(k => k.toLowerCase().includes('live')) ◦ typeof window.livekitClient ◦ window.location.href 2) Confirm exact SDK script tag • In your HTML, ensure you load the UMD build that sets the
livekitClient
global. Use this form (exact URL format matters): <script src="https://cdn.jsdelivr.net/npm/livekit-client@2.16.0/dist/livekit-client.umd.js"></script> • If your page loads a different path (e.g.,
livekit-client.min.js
or missing @version), replace it with the exact line above and reload. 3) Make initialization wait for the SDK (temporary, copy into init.js before calling startInterviewFlow) • Add this wait helper and call it from DOMContentLoaded:
Copy code
function waitForLivekit(timeout = 5000) {
  const start = Date.now();
  return new Promise((resolve, reject) => {
    (function check() {
      if (window.livekitClient && typeof window.livekitClient.connect === 'function') return resolve(window.livekitClient);
      if (Date.now() - start > timeout) return reject(new Error('LiveKit SDK not loaded'));
      setTimeout(check, 50);
    })();
  });
}

document.addEventListener('DOMContentLoaded', async () => {
  try {
    await waitForLivekit(8000);
    console.log('[LiveKitManager] livekitClient available');
    startInterviewFlow();
  } catch (e) {
    console.error('[LiveKitManager] LiveKit SDK not available:', e);
    showError('LiveKit SDK not loaded. Check script tag or network/CSP.');
  }
});
• Remove the previous direct call to startInterviewFlow() so it only runs after waitForLivekit resolves. 4) Network / blocking checks • In DevTools → Network, reload and confirm the SDK file request returns 200. Share the status if it’s not 200. • In Console, look for mixed-content, CSP, or extension blocking errors. Try incognito with extensions disabled. 5) Search & replace incorrect globals • Grep your JS for variants:
LivekitClient
,
LiveKitClient
,
LivekitClient
,
window.LivekitClient
and replace usages with
window.livekitClient
. If you run the console checks from step 1 and share the outputs plus the SDK network status, I’ll point to the exact next change. Sources: Client SDKs | livekit/livekit_composite | DeepWiki
s
Object.keys(window).filter(k => k.toLowerCase().includes('live')) []length: 0[[Prototype]]: Array(0)at: ƒ at()length: 1name: "at"arguments: (...)caller: (...)[[Prototype]]: ƒ ()[[Scopes]]: Scopes[0]concat: ƒ concat()constructor: ƒ Array()copyWithin: ƒ copyWithin()entries: ƒ entries()every: ƒ every()fill: ƒ fill()filter: ƒ filter()find: ƒ find()findIndex: ƒ findIndex()findLast: ƒ findLast()findLastIndex: ƒ findLastIndex()flat: ƒ flat()flatMap: ƒ flatMap()forEach: ƒ forEach()includes: ƒ includes()indexOf: ƒ indexOf()join: ƒ join()keys: ƒ keys()lastIndexOf: ƒ lastIndexOf()length: 0map: ƒ map()pop: ƒ pop()push: ƒ push()reduce: ƒ reduce()reduceRight: ƒ reduceRight()reverse: ƒ reverse()shift: ƒ shift()slice: ƒ slice()some: ƒ some()sort: ƒ sort()splice: ƒ splice()toLocaleString: ƒ toLocaleString()toReversed: ƒ toReversed()toSorted: ƒ toSorted()toSpliced: ƒ toSpliced()toString: ƒ toString()unshift: ƒ unshift()values: ƒ values()with: ƒ with()Symbol(Symbol.iterator): ƒ values()Symbol(Symbol.unscopables): {at: true, copyWithin: true, entries: true, fill: true, find: true, …}[[Prototype]]: Object typeof window.livekitClient 'undefined'
t
Thanks — your console shows no LiveKit global (typeof window.livekitClient === 'undefined'), so the UMD script isn't present in the page runtime. Likely causes: wrong CDN path, script blocked, or script not loaded before your JS runs. Let's fix it with these exact steps. 1) Replace your SDK script tag with this exact line in both pages (put it before any app scripts): <script src="https://cdn.jsdelivr.net/npm/livekit-client@2.16.0/dist/livekit-client.umd.js"></script> 2) Remove any other livekit-client script tags to avoid conflicting paths. 3) Verify it actually loads • Open DevTools → Network → reload the page → search for "livekit-client.umd.js". • Confirm the request returns status 200. If not, tell me the status code you see. 4) If Network shows 200 but global still missing, run this in Console and paste results: • Object.keys(window).filter(k => k.toLowerCase().includes('live')) • typeof window.livekitClient 5) If the request is blocked or fails, check Console for CSP/mixed-content or extension errors. Try an incognito window (extensions disabled) and test again. 6) Apply a safe init guard (temporary) — replace your DOMContentLoaded start with this so init waits for the SDK:
Copy code
async function waitForLivekit(timeout = 8000) {
  const start = Date.now();
  return new Promise((resolve, reject) => {
    (function check(){
      if (window.livekitClient?.connect) return resolve(window.livekitClient);
      if (Date.now() - start > timeout) return reject(new Error('LiveKit SDK not loaded'));
      setTimeout(check, 50);
    })();
  });
}

document.addEventListener('DOMContentLoaded', async () => {
  try {
    await waitForLivekit();
    startInterviewFlow();
  } catch (e) {
    console.error('[LiveKitManager] LiveKit SDK not available:', e);
    showError('LiveKit SDK not loaded. Check script tag or network/CSP.');
  }
});
After you: • Update the script tag to the exact URL in step 1, • Reload and confirm Network status, • Run the two console checks in step 4 and share their outputs, I’ll tell you the precise next step.
s
Request URL https://cdn.jsdelivr.net/npm/livekit-client/dist/livekit-client.min.jsRequest Method GETStatus Code 404 Not FoundReferrer Policy strict-origin-when-cross-origin in network
t
The 404 is the root cause — your page is loading a non‑existent file. Update the SDK script tag to the correct UMD URL and then verify it loads. 1) Replace your current SDK tag in both pages with this exact line (place it before any app scripts): <script src="https://cdn.jsdelivr.net/npm/livekit-client@2.16.0/dist/livekit-client.umd.js"></script> 2) Remove other livekit-client script tags that point to paths that return 404. 3) Verify it loaded: • DevTools → Network → reload → search for "livekit-client.umd.js" → Status should be 200. • In Console run: ◦ Object.keys(window).filter(k => k.toLowerCase().includes('live')) ◦ typeof window.livekitClient Expect to see the global
livekitClient
defined. 4) If the file returns 200 but
window.livekitClient
is still undefined, test in an incognito window (extensions disabled) and share any console CSP/mixed-content messages. Once you confirm the script is 200 and
typeof window.livekitClient === 'object'
, your existing init code should work (or use the wait helper I provided earlier if you want an extra guard). Tell me the Network status and the two console outputs if it still fails.
s
Request URL https://cdn.jsdelivr.net/npm/livekit-client@2.16.0/dist/livekit-client.umd.jsRequest Method GETStatus Code 200 OK (from disk cache)Remote Address 151.101.129.229:443Referrer Policy strict-origin-when-cross-origin but error [LiveKitManager] Available globals with "live": ['LivekitClient'] init.js:80 [LiveKitManager] LiveKit SDK not found or missing connect method! initialize @ init.js:80 startInterviewFlow @ init.js:30 await in startInterviewFlow (anonymous) @ init.js:45Understand this error init.js:111 [LiveKitManager] Error connecting to LiveKit: Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. at LiveKitManager.initialize (init.js8115) at startInterviewFlow (init.js3026) initialize @ init.js:111 startInterviewFlow @ init.js:30 await in startInterviewFlow (anonymous) @ init.js:45Understand this error init.js:277 [LiveKitManager] Error: Failed to connect: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. showError @ init.js:277 initialize @ init.js:112 startInterviewFlow @ init.js:30 await in startInterviewFlow (anonymous) @ init.js:45Understand this error init.js:37 ❌ INTERVIEW FLOW FAILED: Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. at LiveKitManager.initialize (init.js8115) at startInterviewFlow (init.js3026) startInterviewFlow @ init.js:37 await in startInterviewFlow (anonymous) @ init.js:45Understand this error init.js:384 🔴 ERROR: Interview Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script.
t
Thanks — good debugging. Your Network shows the UMD script loads (200), but the global present is
LivekitClient
(capital L, lowercase k) instead of
livekitClient
. Your code checks for
window.livekitClient
, so it still reports "SDK not loaded." Two safe fixes — pick one: Option A — alias the existing global (quick, non-invasive) Add this once before you call initialization (place in your inline script or at top of init.js):
Copy code
// tolerate either global name
if (typeof window.livekitClient === 'undefined' && typeof window.LivekitClient !== 'undefined') {
  window.livekitClient = window.LivekitClient;
}
Option B — check both globals (explicit) Replace your SDK-check with:
Copy code
const livekitGlobal = window.livekitClient || window.LivekitClient || window.LiveKitClient;
if (!livekitGlobal || typeof livekitGlobal.connect !== 'function') {
  throw new Error('LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script.');
}
After applying one of those: 1. Reload and run in Console: ◦ typeof window.livekitClient ◦ typeof window.LivekitClient 1. Confirm both are 'object' (or at least one is defined) and then your existing initialize/connect should proceed. If you prefer, paste the top of your bundle/app.js where you first check the global and I’ll give the exact one-line patch to add. Sources: client-sdk-js | livekit/livekit_composite | DeepWiki
s
[LiveKitManager] Available globals with "live": ['LivekitClient'] init.js:82 [LiveKitManager] LiveKit SDK not found or missing connect method! initialize @ init.js:82 startInterviewFlow @ init.js:30 await in startInterviewFlow (anonymous) @ init.js:45Understand this error api.js:22 Fetch finished loading: POST "http://127.0.0.1:8000/api/port/bO3VRfmxCd1BtQEyuzx5mA==:3jcakwT_pTOyVmJrRxQJ9OtneOxbQKt8k6DHj1Rhiie0jJqnvuQN1TZrGcCBo2WS/". fetchAPI @ api.js:22 fetchInterviewData @ api.js:75 initializeInterview @ api.js:153 startInterviewFlow @ init.js:17 (anonymous) @ init.js:45 init.js:113 [LiveKitManager] Error connecting to LiveKit: Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. at LiveKitManager.initialize (init.js8315) at startInterviewFlow (init.js3026) initialize @ init.js:113 startInterviewFlow @ init.js:30 await in startInterviewFlow (anonymous) @ init.js:45Understand this error init.js:279 [LiveKitManager] Error: Failed to connect: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. showError @ init.js:279 initialize @ init.js:114 startInterviewFlow @ init.js:30 await in startInterviewFlow (anonymous) @ init.js:45Understand this error init.js:37 ❌ INTERVIEW FLOW FAILED: Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. at LiveKitManager.initialize (init.js8315) at startInterviewFlow (init.js3026) startInterviewFlow @ init.js:37 await in startInterviewFlow (anonymous) @ init.js:45Understand this error init.js:381 🔴 ERROR: Interview Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. showError @ init.js:381 startInterviewFlow @ init.js:38 await in startInterviewFlow (anonymous) @ init.js:45Understand this error init.js:355 [Main] Waiting for LiveKit SDK... (attempt 2 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 3 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 4 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 5 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 6 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 7 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 8 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 9 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 10 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 11 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 12 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 13 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 14 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 15 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 16 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 17 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 18 ) init.js:355 [Main] Waiting for LiveKit SDK... (attempt 19 ) init.js:358 [Main] ❌ LiveKit SDK not found after 20 attempts checkAndInit @ init.js:358 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 initializeIfCredentials @ init.js:364Understand this error init.js:359 [Main] Available globals with "live": ['LivekitClient'] checkAndInit @ init.js:359 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 setTimeout checkAndInit @ init.js:356 initializeIfCredentials @ init.js:364Understand this error typeof window.livekitClient 'undefined' typeof window.LivekitClient 'object'
t
You're almost there — the SDK is loaded as
LivekitClient
(capital L, lowercase k), while your code checks for
window.livekitClient
. Add a tiny compatibility shim at the top of your JS (before any LiveKit usage) to alias the global, then verify. Add this at the very top of init.js (or in an inline script right after the SDK script tag):
Copy code
// compatibility alias for UMD global
if (typeof window.livekitClient === 'undefined' && typeof window.LivekitClient !== 'undefined') {
  window.livekitClient = window.LivekitClient;
}
Then reload and confirm in Console: • typeof window.livekitClient • typeof window.LivekitClient Both should show 'object' (or at least
typeof window.livekitClient === 'object'
) and your initialize() should proceed. If it still fails, paste the first 30 lines of init.js after adding the shim and the two console outputs.
s
[LiveKitManager] Available globals with "live": (2) ['LivekitClient', 'livekitClient'] init.js:92 [LiveKitManager] LiveKit SDK not found or missing connect method! initialize @ init.js:92 startInterviewFlow @ init.js:40 await in startInterviewFlow (anonymous) @ init.js:55Understand this error init.js:123 [LiveKitManager] Error connecting to LiveKit: Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. at LiveKitManager.initialize (init.js9315) at startInterviewFlow (init.js4026) initialize @ init.js:123 startInterviewFlow @ init.js:40 await in startInterviewFlow (anonymous) @ init.js:55Understand this error init.js:289 [LiveKitManager] Error: Failed to connect: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. showError @ init.js:289 initialize @ init.js:124 startInterviewFlow @ init.js:40 await in startInterviewFlow (anonymous) @ init.js:55Understand this error init.js:47 ❌ INTERVIEW FLOW FAILED: Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. at LiveKitManager.initialize (init.js9315) at startInterviewFlow (init.js4026) startInterviewFlow @ init.js:47 await in startInterviewFlow (anonymous) @ init.js:55Understand this error init.js:391 🔴 ERROR: Interview Error: LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script. showError @ init.js:391 startInterviewFlow @ init.js:48 await in startInterviewFlow (anonymous) @ init.js:55Understand this error api.js:22 Fetch finished loading: POST "http://127.0.0.1:8000/api/port/bO3VRfmxCd1BtQEyuzx5mA==:3jcakwT_pTOyVmJrRxQJ9OtneOxbQKt8k6DHj1Rhiie0jJqnvuQN1TZrGcCBo2WS/". fetchAPI @ api.js:22 fetchInterviewData @ api.js:75 initializeInterview @ api.js:153 startInterviewFlow @ init.js:27 (anonymous) @ init.js:55 init.js:365 [Main] Waiting for LiveKit SDK... (attempt 3 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 4 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 5 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 6 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 7 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 8 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 9 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 10 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 11 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 12 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 13 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 14 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 15 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 16 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 17 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 18 ) init.js:365 [Main] Waiting for LiveKit SDK... (attempt 19 ) init.js:368 [Main] ❌ LiveKit SDK not found after 20 attempts checkAndInit @ init.js:368 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 initializeIfCredentials @ init.js:374Understand this error init.js:369 [Main] Available globals with "live": (2) ['LivekitClient', 'livekitClient'] checkAndInit @ init.js:369 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 setTimeout checkAndInit @ init.js:366 initializeIfCredentials @ init.js:374Understand this error
t
You're very close — the SDK is loaded but your code still can't find the connect method because the UMD bundle is exposed under a different global name. Do this minimal, guaranteed fix now. 1) Add this shim at the very top of init.js (before any LiveKit usage or your previous wait logic):
Copy code
// compatibility: ensure the expected global exists
if (typeof window.LiveKitClient === 'undefined') {
  if (typeof window.livekitClient !== 'undefined') window.LiveKitClient = window.livekitClient;
  else if (typeof window.LivekitClient !== 'undefined') window.LiveKitClient = window.LivekitClient;
}
2) Update your SDK check to prefer the canonical global and verify connect exists:
Copy code
const livekitGlobal = window.LiveKitClient || window.livekitClient || window.LivekitClient;
if (!livekitGlobal || typeof livekitGlobal.connect !== 'function') {
  throw new Error('LiveKit SDK not loaded. Make sure the LiveKit SDK script is loaded before this script.');
}
3) Reload and confirm in Console (paste results if it still fails): • typeof window.LiveKitClient • typeof window.livekitClient • typeof window.LivekitClient All three should show 'object' (or at least one object) and
typeof (window.LiveKitClient.connect) === 'function'
. If you still see the error, paste the top 40 lines of init.js after adding the shim and the three console outputs — I’ll point exactly to the failing line. Sources: client-sdk-js | livekit/livekit_composite | DeepWiki
s
does it work for server side access like if client is accessig then it will work but is plain js is accesible to server side also
t
Good question — short answer: • The LiveKit Web/UMD JavaScript SDK is designed to run in browsers (or React Native) and relies on browser WebRTC APIs. It is not intended for server-side usage. • For server-side tasks (minting tokens, server-side room management, or running an SFU client), use LiveKit server SDKs or APIs. LiveKit provides server SDKs (e.g., Node, Go — use these to create tokens and manage rooms) and an HTTP API for server operations. • You can run plain JavaScript on the server with Node.js, but you should not use the browser client SDK there. Instead: ◦ Use a LiveKit server SDK for token generation and server operations, or ◦ Call LiveKit's REST/Admin APIs from Node code. If you want, tell me which server language (Node, Go, Python, etc.) and I’ll give a minimal example for generating tokens or calling the API.
s
and for functioanlities like this code import { createLocalTracks, LocalAudioTrack, LocalTrackPublication, LocalVideoTrack, RemoteParticipant, RemoteTrack, Room, RoomEvent, Track } from "livekit-client"; import { finalizeInterviewAnalytics, initializeAnalytics, startAnalyticsPolling, trackTranscription } from "./analytics"; import { startTranscriptionProcessing as audioStartTranscriptionProcessing, stopTranscriptionProcessing as audioStopTranscriptionProcessing } from "./audio"; import { startMonitoring as startObjectDetection } from "./object_detection"; import { appendMessage as uiAppendMessage, appendTranscript as uiAppendTranscript, setMeetingControlsEnabled as uiSetMeetingControlsEnabled } from "./ui"; import { createTranscriptionSocket } from "./ws"; // -------------------- Global State -------------------- let room: Room; let localVideoTrack: LocalVideoTrack | null = null; let localAudioTrack: LocalAudioTrack | null = null; let screenTrack: LocalVideoTrack | null = null; let videoPublication: LocalTrackPublication | null = null; let audioPublication: LocalTrackPublication | null = null; let transcriptionSocket: WebSocket | null = null; let currentRecordingId: string | null = null; let username = ""; let roomName: string | null = null; let interviewId: string = ""; let analyticsPollingId: number | null = null; let analyticsContext: { interview_id: string; candidate_name: string; selected_interviewer: string } | undefined; let mediaRecorder: MediaRecorder | null = null; let recordedChunks: Blob[] = []; let isRecording = false; // DOM Elements let micBtn: HTMLButtonElement; let screenBtn: HTMLButtonElement; let chatBtn: HTMLButtonElement; let endBtn: HTMLButtonElement; let joinBtn: HTMLButtonElement; let usernamePrompt: HTMLDivElement; let conferenceLayout: HTMLDivElement; let localNameSpan: HTMLSpanElement; let videoContainer: HTMLDivElement; let chatInput: HTMLInputElement; let sendBtn: HTMLButtonElement; let messagesDiv: HTMLDivElement; let transcriptDiv: HTMLDivElement; let codeArea: HTMLTextAreaElement; let fullscreenCodeArea: HTMLTextAreaElement; let chatBox: HTMLDivElement; let closeChatBtn: HTMLButtonElement; let editorSection: HTMLDivElement; let toggleCodeEditorBtn: HTMLButtonElement; let closeEditorBtn: HTMLButtonElement; let extendEditorBtn: HTMLButtonElement; let fullscreenEditor: HTMLDivElement; let closeFullscreenBtn: HTMLButtonElement; let submitCodeBtn: HTMLButtonElement; let fullscreenSubmitCodeBtn: HTMLButtonElement; let recordBtn: HTMLButtonElement; // Transcription state const lastInterimBySender: Record<string, HTMLParagraphElement | null> = {}; let _transcriptionAttached = false; function handleDataMessage(msg: string): void { try { const data = JSON.parse(msg); if (!data.type) return; switch (data.type) { case "chat": uiAppendMessage(messagesDiv, data.message, data.sender); break; case "code": codeArea.value = data.code; fullscreenCodeArea.value = data.code; break; } } catch (err) { console.error("[demo] Invalid data message:", err); } } // UI Wrapper functions function appendMessage(message: string, sender: string = "System"): void { uiAppendMessage(messagesDiv, message, sender); } function setMeetingControlsEnabled(enabled: boolean): void { uiSetMeetingControlsEnabled([micBtn, screenBtn, chatBtn, endBtn, sendBtn], enabled); } function appendTranscript(text: string): void { uiAppendTranscript(transcriptDiv, text); } async function startTranscriptionProcessing(): Promise<void> { await audioStartTranscriptionProcessing(localAudioTrack?.mediaStreamTrack ?? null, transcriptionSocket); } function stopTranscriptionProcessing(): void { audioStopTranscriptionProcessing(); } function showMeetingUI(): void { if (usernamePrompt) usernamePrompt.style.display = "none"; if (conferenceLayout) conferenceLayout.style.display = "flex"; } function updateVideoGridLayout(): void { if (!videoContainer) return; const numTiles = videoContainer.getElementsByClassName('video-tile').length; videoContainer.setAttribute('data-count', numTiles.toString()); } function createParticipantContainer(participant: RemoteParticipant): HTMLDivElement { const container = document.createElement("div"); container.id = `participant-${participant.sid}`; container.className = "video-tile"; const nameEl = document.createElement("div"); nameEl.className = "participant-name"; nameEl.textContent = participant.identity; container.appendChild(nameEl); videoContainer.appendChild(container); updateVideoGridLayout(); return container; } function renderRemoteParticipant(participant: RemoteParticipant) { const container = createParticipantContainer(participant); const handleTrack = (track: RemoteTrack) => { if (track.kind === 'video') { const videoEl = track.attach(); container.appendChild(videoEl); } else if (track.kind === 'audio') { const audioEl = track.attach(); container.appendChild(audioEl); } }; // Handle existing tracks participant.trackPublications.forEach(pub => { if (pub.track) { handleTrack(pub.track); } }); // Handle new tracks participant.on(RoomEvent.TrackSubscribed, handleTrack); participant.on("dataReceived", (payload: Uint8Array) => { const msg = new TextDecoder().decode(payload); handleDataMessage(msg); }); } async function startVideo(roomName: string, token: string, identity: string): Promise<void> { if (!roomName || !token || !identity) { alert("Room details are missing. Cannot join."); return; } try { const tracks = await createLocalTracks({ audio: { noiseSuppression: true, echoCancellation: true, autoGainControl: true, sampleRate: 48000, channelCount: 1, }, video: { resolution: { width: 640, height: 480, frameRate: 30, }, } }); for (const track of tracks) { if (track.kind === Track.Kind.Video) { localVideoTrack = track as LocalVideoTrack; } else if (track.kind === Track.Kind.Audio) { localAudioTrack = track as LocalAudioTrack; } } if (!localVideoTrack || !localAudioTrack) { throw new Error("Could not get both audio and video tracks"); } localVideoTrack.source = Track.Source.Camera; await joinRoomWithDetails(roomName, token, identity, { interview_id: roomName, candidate_name: identity, selected_interviewer: "" }); } catch (error) { console.error("[demo] startVideo error:", error); alert("Could not access camera/microphone. Check permissions."); } } // Wrap all UI related code in DOMContentLoaded document.addEventListener('DOMContentLoaded', () => { console.debug("DOM fully loaded and parsed"); // -------------------- HTML Elements -------------------- // camBtn removed - candidates cannot turn off camera micBtn = document.getElementById("micBtn") as HTMLButtonElement; screenBtn = document.getElementById("screenBtn") as HTMLButtonElement; chatBtn = document.getElementById("chatBtn") as HTMLButtonElement; endBtn = document.getElementById("endBtn") as HTMLButtonElement; joinBtn = document.getElementById("joinBtn") as HTMLButtonElement; recordBtn = document.getElementById("recordBtn") as HTMLButtonElement; usernamePrompt = document.getElementById("usernamePrompt") as HTMLDivElement; conferenceLayout = document.querySelector(".conference-layout") as HTMLDivElement; localNameSpan = document.getElementById("localName") as HTMLSpanElement; videoContainer = document.getElementById("video-container") as HTMLDivElement; chatInput = document.getElementById("chatInput") as HTMLInputElement; sendBtn = document.getElementById("sendBtn") as HTMLButtonElement; messagesDiv = document.getElementById("messages") as HTMLDivElement; transcriptDiv = document.getElementById("transcript") as HTMLDivElement; codeArea = document.getElementById("codeArea") as HTMLTextAreaElement; fullscreenCodeArea = document.getElementById("fullscreenCodeArea") as HTMLTextAreaElement; chatBox = document.getElementById("chatBox") as HTMLDivElement; closeChatBtn = document.getElementById("closeChatBtn") as HTMLButtonElement; editorSection = document.getElementById("editorSection") as HTMLDivElement; toggleCodeEditorBtn = document.getElementById("toggleCodeEditorBtn") as HTMLButtonElement; closeEditorBtn = document.getElementById("closeEditorBtn") as HTMLButtonElement; extendEditorBtn = document.getElementById("extendEditorBtn") as HTMLButtonElement; fullscreenEditor = document.getElementById("fullscreenEditor") as HTMLDivElement; closeFullscreenBtn = document.getElementById("closeFullscreenBtn") as HTMLButtonElement; submitCodeBtn = document.getElementById("submitCode") as HTMLButtonElement; fullscreenSubmitCodeBtn = document.getElementById("fullscreenSubmitCode") as HTMLButtonElement; const usernameInput = document.getElementById("usernameInput") as HTMLInputElement; const recStatus = document.getElementById("recStatus") as HTMLDivElement; // -------------------- Initialization -------------------- setMeetingControlsEnabled(false); // The interview.html page dispatches a 'start-call' event with room details. document.addEventListener("start-call", (e: Event) => { const { room, token, identity } = (e as CustomEvent).detail; console.debug("Received start-call event", { room, token, identity }); startVideo(room, token, identity); joinBtn.disabled = true; joinBtn.innerHTML = "Joining..."; }); joinBtn.addEventListener("click", async () => { const identity = usernameInput.value.trim(); if (!identity) { alert("Please enter your name."); return; } const urlParams = new URLSearchParams(window.location.search); const roomName = urlParams.get('room'); const token = urlParams.get('token'); if (roomName && token) { await startVideo(roomName, token, identity); } else { alert('Could not join room, room name or token is missing.'); } }); // -------------------- UI Controls -------------------- // Camera button event listener removed - candidates cannot turn off camera micBtn.addEventListener("click", async () => { if (!audioPublication) return; const isMuted = !!audioPublication.track?.isMuted; await (isMuted ? audioPublication.track?.unmute() : audioPublication.track?.mute()); micBtn.innerHTML = !isMuted ?
<i class="fas fa-microphone-slash"></i>
: `<i class="fas fa-microphone"></i>`; // report mic toggle try { await postEvent({ meeting_id: new URLSearchParams(window.location.search).get('room'), type: isMuted ? 'mic_unmuted' : 'mic_muted', participant: username, timestamp: new Date().toISOString() }); } catch (e) { console.warn('mic event post failed', e); } it can be used in python ?
t
Short answer: No — that browser-oriented JS code (getUserMedia, LocalVideoTrack, attaching HTML <video>, WebSocket transcription from the browser, MediaRecorder) cannot run in Python. Those APIs require a browser (or a native client) and the LiveKit Web SDK. What you can do in Python: • Generate LiveKit access tokens and manage rooms using LiveKit server APIs or a server SDK (use the Node or Go SDKs; LiveKit has an HTTP/admin API you can call from Python). • Call LiveKit REST/Admin endpoints from Python to manage rooms, participants, recordings, and other server-side resources. • Run backend services that process data from clients (e.g., receive transcription events via your server, store analytics, call speech-to-text providers, post messages into rooms via data channels through a client). • Launch a headless client in a language that supports WebRTC (not Python directly) or run a browser automation (e.g., Playwright) if you must run client-side media from a server — but this is complex. If your goal is: • Token generation or room management → I can show a minimal Python example calling the LiveKit HTTP API to create tokens or control rooms. • Server-side transcription/analytics integration → I can outline an architecture (how clients send audio/transcripts to your Python service). • Running a server-side participant (SFU client) → recommend using a language with LiveKit server/client SDK support (Node/Go) or a headless browser approach; I can give specifics. Which of the above do you want a sample for (Python token example, REST call, or architecture for server-side transcription)?
s
so for this insated of node can we use reactframwork for browser oriented and i have used django for backend and python code is there
t
Yes — you can use React (or plain browser JS) for the frontend and keep Django/Python as your backend. Summary and next steps: • Frontend (browser) ◦ Use the LiveKit Web SDK (UMD or ESM) or the React components (
@livekit/components-react
) inside a React app. React is fully supported and a common choice for browser-based apps. ◦ The client SDK runs in the browser and handles WebRTC, local media, publishing/subscribing, data channels, etc. Your React app (or plain JS) will call
connect()
and manage tracks/UI. • Backend (Django / Python) ◦ Use Django to mint LiveKit access tokens and to perform server-side tasks (room setup, storing analytics, webhooks, persistence). Tokens must be created server-side — never create production tokens in client JS. ◦ You can call LiveKit’s REST/Admin API from Python or use server SDKs in other languages (Node/Go) if desired. For most workflows, Django will: i. Authenticate your user ii. Request/create a token for that user/room iii. Return the token to the browser client (over HTTPS) ◦ Django can also receive analytics, transcription results, or webhooks from your client or third-party services. • Example workflow (concise) a. User opens React page → requests to join. b. React requests a token from Django: POST /api/get_livekit_token { room, identity }. c. Django generates token (server-side) and returns it. d. React calls LiveKit client connect(wssUrl, token) and joins room. e. React handles media, data messages, UI. Django stores analytics/events as needed. • Minimal Python token example (concept): ◦ Use server-side LiveKit SDK or JWT libs to create tokens in Django and return JSON { token } to frontend. ◦ I can provide a Django view example if you want. Tell me whether you want: • A minimal React + Django token flow example (code for both sides), or • A plain JS (no framework) + Django example, or • A React example using
@livekit/components-react
for quicker UI.
s
how many egress livekit provides
t
LiveKit’s egress capabilities and limits — concise summary: • Concurrency (how many egress jobs at once) ◦ Free/Build plan: 2 concurrent egress requests by default. ◦ Higher-tier plans allow more concurrent egress; you can request increases via the LiveKit Cloud dashboard. • Egress time limits (per session) ◦ File outputs (MP4/OGG/WebM): up to 3 hours. ◦ HLS segments, HLS/RTMP streaming, and raw track exports: up to 12 hours. ◦ When a session hits its limit it ends with status
LIMIT_REACHED
. • Supported egress types ◦ Room composite (record full room layout) ◦ Web egress (record a website) ◦ Participant/Track egress (single participant or single track) ◦ Track composite (sync/export one audio + one video track) • Output formats ◦ File (MP4/WebM/OGG), HLS segments, RTMP/SRT streaming, and image thumbnails. • Self-hosting option ◦ If you self-host, you can scale egress workers horizontally (Kubernetes/Docker) to increase capacity beyond LiveKit Cloud plan limits. If you want, I can: • Check your current Cloud plan’s exact concurrency limit, or • Provide example egress API requests (room composite or RTMP) for your use case. Which would you prefer? Sources: Quotas and limits | LiveKit docs | Recording and export | LiveKit docs | Egress output types | LiveKit docs | Self-hosting the Egress Service | LiveKit docs
s
means i am using egress free plan so how many egress i will get for particular project ..like 2 recording 3 recording
t
On the free (Build) plan you can run 2 concurrent egress sessions. That means at any one time you can have up to two active recordings/streams (eg. 2 recordings). If you start a third, it will be rejected or queued until one of the two finishes. This concurrency limit is applied to your account (not per individual project). To increase concurrent egress you’ll need a higher plan or request an increase. Would you like example flows for handling concurrency (queueing or retry) in your app?