# How to Integrate Lovable with LiveChat

- Tool: Lovable
- Difficulty: Intermediate
- Time required: 25 minutes
- Last updated: March 2026

## TL;DR

To integrate LiveChat with Lovable, create a LiveChat Developer App to get a Personal Access Token, store it in Cloud → Secrets, then build Edge Functions that call the LiveChat REST API for chats, agents, customers, and chat archives. LiveChat is the ideal choice when you need a focused real-time chat widget embedded in your Lovable app without the broader scope of Intercom or Zendesk.

## Add real-time customer chat and analytics to Lovable with LiveChat's API

LiveChat is purpose-built for one thing: real-time chat between businesses and their customers. Unlike Intercom (which combines messaging, help center, chatbots, and CRM) or Zendesk (which leads with ticketing), LiveChat keeps its focus narrow — a polished chat widget, agent management tools, and chat analytics. For Lovable apps where the primary support channel is live chat rather than tickets or async messaging, LiveChat offers a simpler and more cost-effective integration path.

LiveChat's integration has two components: the widget (a JavaScript-based chat bubble embedded in your frontend) and the REST API (accessed via Edge Functions for analytics, chat management, and customer data). The widget handles real-time chat natively, while the API enables you to build custom dashboards showing chat volume, response times, agent availability, and conversation archives.

Authentication for the LiveChat REST API uses Personal Access Tokens generated in the LiveChat Developer Console. These tokens provide API access scoped to your account permissions. The API base URL is https://api.livechatinc.com/ and the current stable version is v3.6.

The most common Lovable + LiveChat integration patterns are: embedding the chat widget with user identity pre-filled from your app's authenticated session, building internal dashboards showing chat queue status and agent metrics, and fetching chat archives to store conversation history in your Supabase database for compliance or review purposes.

## Before you start

- A Lovable project with Lovable Cloud enabled (Edge Functions require a deployed app)
- A LiveChat account (14-day free trial available at livechat.com — the Starter plan at $20/agent/month is the minimum paid tier)
- Access to the LiveChat Developer Console at developers.livechat.com to create an application
- Your LiveChat License Number (visible in LiveChat settings — required for widget initialization)

## Step-by-step guide

### 1. Create a LiveChat Developer App and get a Personal Access Token

LiveChat API authentication uses Personal Access Tokens generated through the LiveChat Developer Console.

Go to developers.livechat.com and sign in with your LiveChat account. Click 'Create new app' in the top right. Give the app a name like 'Lovable Integration' and select 'Service account credentials' as the app type — this is appropriate for server-side Edge Function integrations.

In the app's Authorization section, you will find the Client ID and Client Secret. However, for Lovable Edge Functions, a Personal Access Token is simpler. To generate one: go to developers.livechat.com → Your Apps → Build → Personal Access Tokens. Click 'Generate a new token'. Select the scopes you need:
- chats--all:read — for reading chat archives and summaries
- reports_read — for accessing analytics and reports
- agents--all:read — for fetching agent information
- customers:read — for accessing customer profiles

Generate the token. Copy the token string — it starts with 'Bearer dal:...' or similar. This is your Personal Access Token for API calls.

Also note your LiveChat License Number — found in LiveChat settings at my.livechatinc.com → Settings → Chat Widget → under 'LiveChat for developers', or visible in your LiveChat URL. The license number is a 5-8 digit number like '12345678'. You need it both for widget initialization and as the account ID for some API calls.

For the chat widget on your Lovable frontend, you need the License Number (not the API token — the License Number is a public identifier safe for client-side code).

**Expected result:** A LiveChat Developer App is created. A Personal Access Token with required scopes is generated and copied. The LiveChat License Number is noted. Both are ready to be stored appropriately (token in Cloud → Secrets, License Number as an env variable).

### 2. Store credentials in Cloud Secrets and add the chat widget to Lovable

Add LiveChat API credentials to Lovable's Cloud Secrets panel. In Lovable, click '+' → Cloud panel → Secrets. Add two secrets:

- LIVECHAT_ACCESS_TOKEN — your Personal Access Token from the Developer Console
- LIVECHAT_ACCOUNT_ID — your LiveChat License Number (also used as account ID in API calls)

For the widget (frontend), you also need the License Number as a build-time environment variable. In Lovable, this should be set as VITE_LIVECHAT_LICENSE_ID in your app's environment configuration — it is public and safe for the browser bundle.

The LiveChat widget is a JavaScript snippet that initializes in the browser. The simplest implementation for React is to load the LiveChat script in your app's main component and initialize it with the license number. When a user is logged in, use the LiveChat JavaScript API to set their name and email: window.LiveChatWidget.call('set_customer_name', name) and window.LiveChatWidget.call('set_customer_email', email).

LiveChat's JavaScript widget API also supports custom variables for passing plan tier, user ID, or any metadata to agents: window.LiveChatWidget.call('set_session_variables', { plan: 'pro', userId: user.id }).

The LiveChat REST API base URL is https://api.livechatinc.com/ with version prefix v3.6 for most endpoints.

```
// src/components/LiveChatWidget.tsx
import { useEffect } from 'react'
import { useAuth } from '@/hooks/useAuth'

declare global {
  interface Window {
    LiveChatWidget: {
      call: (method: string, ...args: unknown[]) => void
      on: (event: string, callback: (data: unknown) => void) => void
    }
    __lc: { license: number; asyncInit: boolean }
  }
}

export function LiveChatWidget() {
  const { user } = useAuth()
  const licenseId = import.meta.env.VITE_LIVECHAT_LICENSE_ID

  useEffect(() => {
    if (!licenseId) return

    window.__lc = window.__lc || {}
    window.__lc.license = parseInt(licenseId)
    window.__lc.asyncInit = true

    const script = document.createElement('script')
    script.async = true
    script.src = 'https://cdn.livechatinc.com/tracking.js'
    document.head.appendChild(script)

    return () => {
      document.head.removeChild(script)
    }
  }, [licenseId])

  useEffect(() => {
    if (!window.LiveChatWidget || !user) return
    window.LiveChatWidget.call('set_customer_email', user.email || '')
    window.LiveChatWidget.call('set_customer_name', user.user_metadata?.full_name || user.email || '')
    window.LiveChatWidget.call('set_session_variables', {
      user_id: user.id,
    })
  }, [user])

  return null
}
```

**Expected result:** The LiveChat chat bubble appears in the bottom-right corner of your deployed Lovable app. Logged-in users have their name and email pre-filled when starting a chat, visible to agents in the LiveChat agent workspace.

### 3. Create the LiveChat REST API proxy Edge Function

Build the Edge Function that queries LiveChat's REST API for analytics, chat archives, and agent data. These operations require the access token and cannot be performed from the browser.

LiveChat REST API v3.6 key endpoints:
- GET /v3.6/configuration/agents — list all agents with availability status
- GET /v3.6/reports/chats/total_chats — total chat count for a date range
- GET /v3.6/reports/chats/agents — per-agent chat statistics
- GET /v3.6/reports/chats/first_response_time — average response time
- GET /v3.6/reports/ratings/chats_count — satisfaction ratings count
- GET /v3.6/chats — list chat summaries (archives)
- GET /v3.6/chats/{chat_id} — get full chat transcript

Authentication: Bearer token in the Authorization header plus the X-Region header if your account is in the European data center (dal.eu region). Most accounts are in the default US region.

Date parameters in LiveChat analytics endpoints use ISO 8601 format: from and to parameters as YYYY-MM-DDThh:mm:ssZ. The reports are paginated with page parameter starting at 1.

The chat archive (GET /v3.6/chats) returns chat summaries with ID, timestamps, agent, and ratings. To get the full message transcript, call GET /v3.6/chats/{chatId} with the specific chat ID.

```
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

const LC_BASE = 'https://api.livechatinc.com/v3.6'

function livechatHeaders() {
  const token = Deno.env.get('LIVECHAT_ACCESS_TOKEN')
  if (!token) throw new Error('LIVECHAT_ACCESS_TOKEN not configured')
  return {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
  }
}

serve(async (req) => {
  if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })

  try {
    const { action, params = {} } = await req.json()
    const headers = livechatHeaders()
    let resp: Response

    switch (action) {
      case 'list_agents':
        resp = await fetch(`${LC_BASE}/configuration/agents`, { headers })
        break

      case 'get_chat_stats': {
        const from = params.from || new Date(Date.now() - 30 * 86400000).toISOString().split('T')[0]
        const to = params.to || new Date().toISOString().split('T')[0]
        resp = await fetch(`${LC_BASE}/reports/chats/total_chats?from=${from}T00:00:00Z&to=${to}T23:59:59Z&distribution=day`, { headers })
        break
      }

      case 'list_chat_archives':
        resp = await fetch(`${LC_BASE}/chats?${new URLSearchParams({
          page_id: params.pageId || '',
          sort_order: 'desc',
          ...(params.agentId && { filters: JSON.stringify({ agent_ids: [params.agentId] }) }),
        }).toString()}`, { headers })
        break

      case 'get_chat_transcript':
        resp = await fetch(`${LC_BASE}/chats/${params.chatId}`, { headers })
        break

      default:
        return new Response(JSON.stringify({ error: 'Unknown action' }), {
          status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
        })
    }

    const data = await resp.json()
    return new Response(JSON.stringify(data), {
      status: resp.ok ? 200 : resp.status,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    })
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    })
  }
})
```

**Expected result:** The livechat-api Edge Function deploys in Cloud → Edge Functions. Test with action 'list_agents' — your LiveChat agent list should appear in the response with their availability status.

## Best practices

- Always pre-fill user identity (name and email) in the LiveChat widget for logged-in users — agents can provide better support when they immediately know who they are chatting with.
- Pass relevant context as session variables (plan tier, account age, last error) alongside user identity — this gives agents the information they need without asking the customer to repeat it.
- Use Personal Access Tokens with minimum required scopes rather than broad permissions — read-only tokens for analytics are safer than full-access tokens.
- Cache LiveChat analytics data in Supabase rather than fetching from the API on every dashboard load — chat metrics rarely change more than once per hour.
- Implement LiveChat availability detection in your app to show a contact form or async messaging option when no agents are online — do not leave users with an empty 'unavailable' widget.
- Store chat IDs for important conversations in your Supabase database when you need to retrieve transcripts later — the LiveChat archive API is paginated and searching for specific chats by customer email requires iterating through pages.
- Test the widget with Lovable's deployed app URL, not the editor preview — LiveChat may block widget initialization on localhost or non-registered domains.

## Use cases

### Embed LiveChat widget with authenticated user identity

Add the LiveChat widget to your Lovable app so that when logged-in users start a chat, their name and email are automatically sent to the agent rather than requiring manual identification. The widget is initialized with user data from your Supabase Auth session, and agents see the customer's name, email, and any custom properties you pass (plan tier, account age, etc.) in the chat window.

Prompt example:

```
Add the LiveChat widget to my Lovable app. When a user is logged in, initialize the LiveChat widget with their name (from user_metadata.full_name) and email. Also pass a custom variable 'plan' with their current subscription tier. When logged out, show the widget without pre-filled data. Use the VITE_LIVECHAT_LICENSE_ID environment variable for the license number.
```

### Chat analytics dashboard showing agent performance and volume

Build an internal operations dashboard that fetches LiveChat analytics data: total chats by day, average response time, chat satisfaction ratings, and agent availability status. Managers see team performance at a glance without logging into LiveChat's reporting interface. The dashboard refreshes daily to show current metrics alongside historical trends.

Prompt example:

```
Create an Edge Function called livechat-analytics that fetches chat volume, response time, and satisfaction ratings from the LiveChat Reports API using LIVECHAT_ACCESS_TOKEN and LIVECHAT_ACCOUNT_ID from secrets. Date range: last 30 days. Return total_chats, avg_response_time_seconds, satisfaction_good_count, and daily breakdown. Build a metrics dashboard in Lovable with KPI cards and a line chart for daily chat volume.
```

### Chat archive viewer for compliance and review

Create an internal tool that fetches LiveChat chat archives for a specific date range or agent, displays full conversation transcripts, and allows managers to flag conversations for review. Chat transcripts are stored in Supabase for compliance purposes and searchable by keyword, date, or customer email — enabling quality assurance reviews without direct LiveChat access for every manager.

Prompt example:

```
Create an Edge Function called livechat-archives that accepts { startDate, endDate, agentId } and fetches chat transcripts from the LiveChat Chats API using LIVECHAT_ACCESS_TOKEN and LIVECHAT_ACCOUNT_ID from secrets. Return chat ID, start time, agent name, customer email, rating, and message count. Build an archive viewer page with date range picker, agent filter, and expandable chat transcripts.
```

## Troubleshooting

### LiveChat API returns 401 Unauthorized with 'invalid access token' error

Cause: The Personal Access Token is incorrect, has expired, or was generated with insufficient scopes for the endpoint being called.

Solution: In the LiveChat Developer Console, verify the Personal Access Token is active and has the required scopes (chats--all:read, reports_read, agents--all:read). Generate a new token if needed and update the LIVECHAT_ACCESS_TOKEN secret. Personal Access Tokens in LiveChat expire after a configurable period — check the token's expiry in the Developer Console.

### LiveChat chat widget does not appear on the Lovable app

Cause: The VITE_LIVECHAT_LICENSE_ID environment variable is not set, or the script is blocked by a Content Security Policy on the deployment.

Solution: Verify VITE_LIVECHAT_LICENSE_ID is configured as a build-time environment variable accessible via import.meta.env. Also check browser console for any CSP errors — LiveChat's CDN (cdn.livechatinc.com) must be allowed by your app's Content Security Policy. In Lovable, check if any custom headers are blocking external scripts.

### Chat analytics returns empty data for the date range specified

Cause: The date format is incorrect for the LiveChat reports API, or no chats occurred in the specified date range.

Solution: LiveChat reports require ISO 8601 datetime with timezone: YYYY-MM-DDThh:mm:ssZ. Ensure the 'from' and 'to' parameters include the time component and 'Z' timezone suffix. A common mistake is using YYYY-MM-DD format (date only) which the reports API does not accept.

```
// Correct date format for LiveChat Reports API:
const from = '2026-01-01T00:00:00Z'  // MUST include time and Z suffix
const to = '2026-03-31T23:59:59Z'
```

### LiveChat widget shows the chat button but opening it shows 'Chat is currently unavailable'

Cause: No agents are currently online in LiveChat, or after-hours settings show the widget as unavailable.

Solution: This is expected behavior when all agents are offline or during configured unavailable hours. In LiveChat settings, you can configure the widget to show a contact form during offline hours instead of the unavailability message. Use the LiveChat JavaScript API to detect availability status: window.LiveChatWidget.on('availability_changed', handler) to update your UI based on chat availability.

## Frequently asked questions

### Does LiveChat have a free plan?

LiveChat does not have a permanent free plan. A 14-day free trial is available, and the Starter plan is $20/agent/month billed annually. The Starter plan includes the chat widget, basic analytics, and API access. For small teams building Lovable integrations, the 14-day trial is sufficient for development and testing before committing to a plan.

### Can I use LiveChat for both web and mobile apps built with Lovable?

Lovable builds web apps (React + Vite), not native mobile apps. The LiveChat JavaScript widget works in web browsers, including mobile browsers. If your Lovable app is accessed via mobile browser, the LiveChat widget is fully functional. For native iOS/Android apps, LiveChat offers separate mobile SDKs, but those are outside the scope of Lovable's web-based development.

### How do I prevent the LiveChat widget from appearing on every page (like the admin dashboard)?

Use LiveChat's JavaScript API to conditionally show or hide the widget based on the current route. In your React app, add a useEffect that watches the router location and calls window.LiveChatWidget.call('hide') on admin-only pages, and window.LiveChatWidget.call('minimize') or window.LiveChatWidget.call('maximize') on customer-facing pages. The LiveChat widget respects these programmatic show/hide calls.

### What is the difference between LiveChat and LiveChat's Chatbot product?

LiveChat is the human-agent chat product — real support agents receive and respond to chat conversations. ChatBot.com is a separate Livechat Inc. product for building automated chatbot flows that can answer questions without human agents. The two products integrate: ChatBot handles first-contact resolution attempts and escalates to LiveChat human agents when needed. This guide covers the LiveChat human-agent product. Building chatbot flows requires the separate ChatBot.com API integration.

---

Source: https://www.rapidevelopers.com/lovable-integration/livechat
© RapidDev — https://www.rapidevelopers.com/lovable-integration/livechat
