Skip to main content
RapidDev - Software Development Agency
replit-integrationsStandard API Integration

How to Integrate Replit with LiveChat

To integrate Replit with LiveChat, generate an API key from your LiveChat agent account, store it and your account login in Replit Secrets (lock icon πŸ”’), and call the LiveChat REST API from your Python or Node.js server to retrieve chat history, manage agents, and receive real-time events via webhooks. Use Reserved VM deployment for webhook-heavy chat monitoring applications.

What you'll learn

  • How to generate a LiveChat API key and configure Replit Secrets
  • How to retrieve chat transcripts and customer data using Python and Node.js
  • How to manage agents and queue status via the LiveChat Configuration API
  • How to set up LiveChat webhooks to receive real-time chat events in your Replit server
  • How to build a chat analytics dashboard by aggregating LiveChat API data
Book a free consultation
4.9Clutch rating ⭐
600+Happy partners
17+Countries served
190+Team members
Intermediate14 min read25 minutesCommunicationMarch 2026RapidDev Engineering Team
TL;DR

To integrate Replit with LiveChat, generate an API key from your LiveChat agent account, store it and your account login in Replit Secrets (lock icon πŸ”’), and call the LiveChat REST API from your Python or Node.js server to retrieve chat history, manage agents, and receive real-time events via webhooks. Use Reserved VM deployment for webhook-heavy chat monitoring applications.

Why Connect Replit to LiveChat?

LiveChat is used by over 37,000 businesses as the primary customer communication channel on their websites. Its API exposes everything the agent dashboard shows β€” chat transcripts, customer information, queue status, agent availability, and canned responses β€” making it possible to build custom integrations, analytics dashboards, and automated workflows that the native LiveChat interface does not support.

The most common integration patterns are: pulling chat transcripts for post-chat analysis and quality scoring, routing chats to the right agent or team based on customer data from your database, and triggering follow-up workflows in your CRM when a chat ends. LiveChat's webhook system delivers events in near real-time, so your Replit server can react instantly to new chats, chat completions, and customer messages.

Replit's Secrets system (lock icon πŸ”’ in the sidebar) keeps your LiveChat API key and login email encrypted and inaccessible from client-side code. LiveChat uses Basic Auth where the username is your login email and the password is the API key β€” both values together grant full access to your LiveChat account data, so they must only be used in server-side backend code.

Integration method

Standard API Integration

You connect Replit to LiveChat by generating an API key in your LiveChat agent account settings, storing it alongside your account login email in Replit Secrets, and calling the LiveChat Configuration API and Web API from your server-side Python or Node.js code. LiveChat uses HTTP Basic Authentication with your account login as the username and API key as the password. Webhooks deliver real-time chat events to your deployed Replit server.

Prerequisites

  • A Replit account with a Python or Node.js project created
  • A LiveChat account with agent access (Starter plan or higher for API access)
  • Your LiveChat account login email address
  • Basic familiarity with REST APIs and HTTP Basic Authentication
  • Python 3.10+ or Node.js 18+ (both available on Replit by default)

Step-by-step guide

1

Generate a LiveChat API Key and Store Credentials

Log in to your LiveChat agent account at my.livechat.com. Click your profile icon in the bottom-left corner and select 'Profile'. On the profile page, click on the 'API Keys' tab. You will see a section called 'Personal Access Tokens'. Click 'Create token', give it a descriptive name like 'replit-integration', and copy the generated token. Alternatively, you can use your account's API key found at the bottom of the profile page under the 'Legacy API Key' section. The newer Personal Access Tokens are recommended for new integrations as they offer better scoping. You also need your LiveChat account login (the email address you use to sign in). LiveChat uses HTTP Basic Authentication where the username is your login email and the password is the API key (or personal access token). Open your Replit project and click the lock icon πŸ”’ in the left sidebar. Add two Secrets: - LIVECHAT_LOGIN: your LiveChat account email - LIVECHAT_API_KEY: your API key or personal access token Access them in Python with os.environ['LIVECHAT_LOGIN'] and os.environ['LIVECHAT_API_KEY']. In Node.js use process.env.LIVECHAT_LOGIN and process.env.LIVECHAT_API_KEY.

Pro tip: LiveChat has two main API versions: the Configuration API (v3, at api.livechatinc.com/v3) for managing agents, groups, and chat routing, and the Web API (v2, at api.livechatinc.com/v2) for accessing chat transcripts and reports. Both use the same Basic Auth credentials.

Expected result: LIVECHAT_LOGIN and LIVECHAT_API_KEY secrets appear in the Replit Secrets pane. A test API call returns a 200 response confirming the credentials are valid.

2

Retrieve Chat Transcripts and Customer Data in Python

The LiveChat REST API uses Basic Authentication where the username is your account email and the password is the API key. The base URL for v2 endpoints (chats, agents, reports) is https://api.livechatinc.com/v2, and the Configuration API v3 base URL is https://api.livechatinc.com/v3. Chat transcripts are available via GET /chats, which returns paginated chat records including the customer's name, email, and the full message history. The chats endpoint supports date range filtering with date_from and date_to parameters, making it easy to pull transcripts for a specific day or shift. The Python code below demonstrates how to fetch recent chats with customer information, retrieve detailed transcript content, and list available agents with their current status. The requests library handles Basic Auth natively β€” pass a tuple of (login, api_key) to the auth parameter.

livechat_client.py
1import os
2import requests
3from datetime import datetime, timedelta
4from typing import Optional
5
6LOGIN = os.environ["LIVECHAT_LOGIN"]
7API_KEY = os.environ["LIVECHAT_API_KEY"]
8AUTH = (LOGIN, API_KEY) # Basic Auth tuple
9V2_BASE = "https://api.livechatinc.com/v2"
10
11HEADERS = {
12 "Content-Type": "application/json",
13 "X-API-Version": "2"
14}
15
16def get_chats(date_from: str = None, date_to: str = None,
17 agent_login: str = None, page: int = 1) -> dict:
18 """Fetch chat transcripts with optional filters."""
19 if not date_from:
20 yesterday = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
21 date_from = yesterday
22 if not date_to:
23 date_to = datetime.now().strftime("%Y-%m-%d")
24
25 params = {
26 "date_from": date_from,
27 "date_to": date_to,
28 "page": page
29 }
30 if agent_login:
31 params["agent"] = agent_login
32
33 response = requests.get(
34 f"{V2_BASE}/chats",
35 params=params,
36 auth=AUTH,
37 headers=HEADERS
38 )
39 response.raise_for_status()
40 return response.json()
41
42def get_chat_by_id(chat_id: str) -> dict:
43 """Get the full transcript for a specific chat."""
44 response = requests.get(
45 f"{V2_BASE}/chats/{chat_id}",
46 auth=AUTH,
47 headers=HEADERS
48 )
49 response.raise_for_status()
50 return response.json()
51
52def get_agents() -> list:
53 """List all agents and their current availability status."""
54 response = requests.get(
55 f"{V2_BASE}/agents",
56 auth=AUTH,
57 headers=HEADERS
58 )
59 response.raise_for_status()
60 return response.json()
61
62def get_chat_stats(date_from: str, date_to: str) -> dict:
63 """Get aggregate chat statistics for a date range."""
64 params = {"date_from": date_from, "date_to": date_to}
65 response = requests.get(
66 f"{V2_BASE}/reports/chats/total_chats",
67 params=params,
68 auth=AUTH,
69 headers=HEADERS
70 )
71 response.raise_for_status()
72 return response.json()
73
74# Example usage
75if __name__ == "__main__":
76 agents = get_agents()
77 print(f"Total agents: {len(agents)}")
78 for agent in agents[:5]:
79 print(f" {agent.get('login')}: {agent.get('status')}")
80
81 chats = get_chats()
82 total = chats.get('total', 0)
83 print(f"\nChats from yesterday: {total}")
84
85 chat_list = chats.get('chats', [])
86 if chat_list:
87 first_chat = get_chat_by_id(chat_list[0]['id'])
88 messages = first_chat.get('messages', [])
89 print(f"\nFirst chat ({len(messages)} messages):")
90 for msg in messages[:3]:
91 print(f" [{msg.get('author_name')}]: {msg.get('text', '')[:80]}")

Pro tip: LiveChat v2 API paginates chat results at 150 chats per page. For full date range exports, loop through pages until the returned count is less than 150 or until the page response is empty.

Expected result: The script prints your agent list with statuses and a count of yesterday's chats. Running it confirms the credentials are valid and the API is accessible from Replit.

3

Build a Node.js Integration with Agent Management

The Node.js integration uses the same Basic Auth credentials. The Express server below exposes endpoints for fetching chat history (useful for building a custom dashboard), checking agent status, and creating tickets from chat data. Install dependencies with 'npm install express axios' in the Replit shell. LiveChat's Configuration API v3 provides more granular control over routing and agent management than v2. To use v3 endpoints, include the version in the URL path and add the X-Api-Version: 3 header. The Configuration API is particularly useful for setting agent availability status programmatically β€” for example, automatically setting agents to 'away' outside of business hours. The server also includes a /stats endpoint that aggregates chat metrics, which you can use as a feed for a status board or Slack notification. Response time metrics help identify when the support queue is falling behind and additional agents need to be scheduled.

server.js
1const express = require('express');
2const axios = require('axios');
3
4const app = express();
5app.use(express.json());
6
7const LOGIN = process.env.LIVECHAT_LOGIN;
8const API_KEY = process.env.LIVECHAT_API_KEY;
9
10// Create axios instance with Basic Auth
11const livechat = axios.create({
12 baseURL: 'https://api.livechatinc.com/v2',
13 auth: { username: LOGIN, password: API_KEY },
14 headers: { 'Content-Type': 'application/json', 'X-API-Version': '2' }
15});
16
17// Get recent chats with customer info
18app.get('/chats', async (req, res) => {
19 const { date_from, date_to, page = 1 } = req.query;
20 try {
21 const params = {
22 date_from: date_from || new Date(Date.now() - 86400000).toISOString().split('T')[0],
23 date_to: date_to || new Date().toISOString().split('T')[0],
24 page: parseInt(page)
25 };
26 const { data } = await livechat.get('/chats', { params });
27 const simplified = (data.chats || []).map(chat => ({
28 id: chat.id,
29 started: chat.started,
30 ended: chat.ended,
31 customerName: chat.visitor?.name,
32 customerEmail: chat.visitor?.email,
33 agentName: chat.agents?.[0]?.display_name,
34 rating: chat.rate,
35 messageCount: chat.messages?.length || 0
36 }));
37 res.json({ total: data.total, chats: simplified });
38 } catch (err) {
39 console.error('Chats error:', err.response?.data || err.message);
40 res.status(500).json({ error: err.message });
41 }
42});
43
44// Get all agents with current status
45app.get('/agents', async (req, res) => {
46 try {
47 const { data } = await livechat.get('/agents');
48 res.json(data);
49 } catch (err) {
50 res.status(500).json({ error: err.message });
51 }
52});
53
54// Get chat statistics for a date range
55app.get('/stats', async (req, res) => {
56 const { date_from, date_to } = req.query;
57 try {
58 const params = {
59 date_from: date_from || new Date(Date.now() - 7 * 86400000).toISOString().split('T')[0],
60 date_to: date_to || new Date().toISOString().split('T')[0]
61 };
62 const [totalChats, responseTime, ratings] = await Promise.all([
63 livechat.get('/reports/chats/total_chats', { params }),
64 livechat.get('/reports/chats/first_response_time', { params }),
65 livechat.get('/reports/chats/ratings', { params })
66 ]);
67 res.json({
68 total: totalChats.data,
69 responseTime: responseTime.data,
70 ratings: ratings.data
71 });
72 } catch (err) {
73 console.error('Stats error:', err.response?.data || err.message);
74 res.status(500).json({ error: err.message });
75 }
76});
77
78app.get('/health', (req, res) => res.json({ status: 'ok' }));
79
80app.listen(3000, '0.0.0.0', () => {
81 console.log('LiveChat integration server running on port 3000');
82});

Pro tip: The /reports endpoint on LiveChat v2 API supports multiple metric types including total_chats, first_response_time, response_time, chats_first_response_time, and ratings. Check the LiveChat API docs for the full list of available report endpoints.

Expected result: The server starts and GET /agents returns your LiveChat agent list. GET /stats returns chat metrics for the default 7-day window.

4

Configure Webhooks and Deploy

LiveChat webhooks notify your Replit server in real time when chat events occur β€” a new chat starts, a chat ends, a customer leaves a rating, or an agent changes status. This is far more efficient than polling the API every few seconds. To set up webhooks, go to your LiveChat dashboard at my.livechat.com, navigate to Settings > Integrations > Webhooks, and click 'Add Webhook'. Select the event type (e.g., 'Chat Started', 'Chat Ended', 'Rating Added'), enter your deployed Replit server URL as the target (e.g., https://your-app.replit.app/livechat/webhook), and save. Webhooks require a deployed URL β€” development session URLs go offline when you close the Replit IDE. Click 'Deploy' in Replit and choose Reserved VM if your app is primarily a chat monitoring service that must respond to events instantly. Choose Autoscale if webhook processing is one of several features in your app. LiveChat retries failed webhook deliveries a limited number of times, so ensure your endpoint responds with 200 promptly.

webhook_server.py
1from flask import Flask, request, jsonify
2import os
3import hmac
4import hashlib
5
6app = Flask(__name__)
7WEBHOOK_SECRET = os.environ.get("LIVECHAT_WEBHOOK_SECRET", "")
8
9@app.route('/livechat/webhook', methods=['POST'])
10def livechat_webhook():
11 # Optional: verify webhook signature if you set a secret key
12 if WEBHOOK_SECRET:
13 signature = request.headers.get('X-LiveChat-Signature', '')
14 expected = hmac.new(
15 WEBHOOK_SECRET.encode(),
16 request.data,
17 hashlib.sha256
18 ).hexdigest()
19 if not hmac.compare_digest(signature, expected):
20 return jsonify({'error': 'Invalid signature'}), 403
21
22 data = request.get_json(force=True)
23 if not data:
24 return jsonify({'error': 'No data'}), 400
25
26 event_type = data.get('event_type', 'unknown')
27 chat_id = data.get('chat', {}).get('id', 'unknown')
28
29 print(f"LiveChat webhook: {event_type} for chat {chat_id}")
30
31 if event_type == 'chat_ended':
32 visitor = data.get('visitor', {})
33 customer_email = visitor.get('email', '')
34 agent = data.get('agents', [{}])[0]
35 agent_name = agent.get('display_name', 'unknown')
36 print(f"Chat ended: {customer_email} with agent {agent_name}")
37 # Update CRM, send to analytics, etc.
38
39 elif event_type == 'rating_added':
40 rating = data.get('rating', {}).get('score', 0)
41 print(f"Rating received: {rating}/5 for chat {chat_id}")
42 # Log to database, trigger follow-up if low rating
43
44 elif event_type == 'new_chat_started':
45 visitor_name = data.get('visitor', {}).get('name', 'Anonymous')
46 print(f"New chat from: {visitor_name}")
47
48 return jsonify({'status': 'received'}), 200
49
50@app.route('/health', methods=['GET'])
51def health():
52 return jsonify({'status': 'ok'}), 200
53
54if __name__ == '__main__':
55 app.run(host='0.0.0.0', port=3000)

Pro tip: LiveChat webhook payloads contain the full chat and visitor data, so you rarely need to make a follow-up API call to get more information. Log the raw payload during development to understand the complete data structure.

Expected result: LiveChat sends a test webhook to your deployed Replit server URL and your server logs the event type and chat ID. The LiveChat webhook settings page shows the webhook status as active.

Common use cases

Automated Post-Chat CRM Updates

When a LiveChat conversation ends, your Replit server receives the webhook event, retrieves the full chat transcript, and creates or updates a contact record in your CRM with the chat summary, customer email, and any information collected during the conversation. Sales teams can see every support interaction without switching between tools.

Replit Prompt

Build a Flask server that receives LiveChat 'chat_deactivated' webhook events, fetches the full chat transcript from the LiveChat API, and creates a note on the corresponding contact in HubSpot using the customer's email as the lookup key.

Copy this prompt to try it in Replit

Real-Time Chat Queue Dashboard

A Replit Express server exposes a dashboard API that aggregates LiveChat queue data β€” active chats, agents online, average response time, and customer wait time β€” into a JSON feed consumed by an internal status board. The dashboard refreshes every 30 seconds and alerts the team when the queue exceeds a threshold.

Replit Prompt

Create a Node.js API server that polls the LiveChat Configuration API every 30 seconds for agent availability and queue status, caches the results, and exposes a /dashboard endpoint that returns current support metrics in JSON format.

Copy this prompt to try it in Replit

Chat Analytics and Quality Scoring

A Replit Python script runs nightly to fetch the previous day's chat transcripts, analyze response times, resolution rates, and customer satisfaction scores, and write summary statistics to a database or spreadsheet. This gives managers a daily view of support team performance without needing access to the LiveChat dashboard.

Replit Prompt

Write a Python script that fetches all chats from the previous day via the LiveChat API, calculates average response time and customer rating for each agent, and writes the results to a CSV file.

Copy this prompt to try it in Replit

Troubleshooting

All API requests return 401 Unauthorized

Cause: Basic Auth credentials are incorrect. LiveChat requires the account login email as the username and the API key as the password β€” not the agent's display name or the account owner name.

Solution: Verify that LIVECHAT_LOGIN contains the exact email address used to log in to LiveChat (not a display name). Confirm LIVECHAT_API_KEY contains the API key or Personal Access Token from the profile page, with no extra whitespace. Test with a simple GET /agents call first to validate credentials.

typescript
1# Python: test credentials with simplest endpoint
2import requests, os
3response = requests.get(
4 'https://api.livechatinc.com/v2/agents',
5 auth=(os.environ['LIVECHAT_LOGIN'], os.environ['LIVECHAT_API_KEY']),
6 headers={'X-API-Version': '2'}
7)
8print(response.status_code, response.text[:200])

Chat transcript API returns empty chats array even for dates with real chats

Cause: The date_from and date_to parameters must use the format YYYY-MM-DD in your account's timezone, not UTC. If your LiveChat account is set to a timezone that is ahead of UTC, using today's UTC date may return an empty result because the 'today' in your timezone has already passed for UTC.

Solution: Use the date in your LiveChat account's configured timezone rather than UTC. Alternatively, use a wider date range (e.g., yesterday through tomorrow) to ensure you capture all relevant chats. Check your account timezone in LiveChat Settings > General.

Webhook events stop arriving after the Replit server is redeployed

Cause: The deployment URL changed after redeployment, or the server is returning non-200 responses to webhook deliveries, causing LiveChat to disable the webhook after repeated failures.

Solution: Replit Autoscale and Reserved VM deployments maintain the same URL across redeployments. Check LiveChat webhook settings to confirm the URL is still registered. If the webhook was disabled due to failures, re-enable it in LiveChat Settings > Integrations > Webhooks. Ensure your endpoint always returns 200 even for unrecognized event types.

API returns 403 Forbidden when trying to access reports endpoints

Cause: Report endpoints in LiveChat require the account owner role or the Billing Manager role. Regular agent accounts do not have permission to access aggregate reporting data.

Solution: Generate the API key from the account owner's profile rather than a regular agent profile. The account owner's credentials give access to all API endpoints including reports. Check the agent's role in LiveChat Settings > Agents.

Best practices

  • Store LIVECHAT_LOGIN and LIVECHAT_API_KEY in Replit Secrets (lock icon πŸ”’) β€” both credentials together provide full account access and must never appear in client-side code.
  • Generate the API key from the LiveChat account owner profile for access to reporting endpoints β€” regular agent keys have restricted report access.
  • Use Personal Access Tokens (available in newer LiveChat accounts) over legacy API keys for better security scoping and token management.
  • Paginate chat history requests β€” the LiveChat v2 /chats endpoint returns 150 records per page, so loop through all pages when fetching a full date range.
  • Deploy your Replit app before configuring LiveChat webhooks β€” use a stable replit.app deployment URL to prevent dead webhook registrations.
  • Always return HTTP 200 from your webhook handler promptly, even if processing fails internally β€” return errors in the response body rather than as HTTP error codes to prevent LiveChat from disabling the webhook.
  • Use Reserved VM deployment for real-time chat monitoring services where latency matters, and Autoscale for batch analytics jobs that run on a schedule.
  • Log webhook payloads during development to understand the full data structure β€” LiveChat webhook payloads are comprehensive and usually contain everything you need without follow-up API calls.

Alternatives

Frequently asked questions

How do I store my LiveChat API key in Replit?

Click the lock icon πŸ”’ in the left sidebar of your Replit project. Add LIVECHAT_LOGIN with your LiveChat account email address, and LIVECHAT_API_KEY with your API key or Personal Access Token from the LiveChat profile page. Both values are needed because LiveChat uses HTTP Basic Auth where the email is the username and the key is the password.

Does Replit work with LiveChat on the free plan?

The LiveChat Starter plan includes API access, which is the minimum plan needed for server integrations. Replit's free tier supports outbound API calls to LiveChat without restrictions. Always-on webhook reception requires Replit's paid plan, since free Replit projects go to sleep after inactivity.

How do I receive real-time chat events from LiveChat?

Set up a webhook in LiveChat Settings > Integrations > Webhooks, pointing to your deployed Replit server URL. LiveChat sends a JSON POST to your endpoint when events occur (chat started, chat ended, rating added). Your endpoint must return HTTP 200 to confirm receipt. Webhooks only work with a deployed URL β€” not a development session URL.

Can I access chat transcripts from the LiveChat API?

Yes. Use GET https://api.livechatinc.com/v2/chats with date_from and date_to parameters to retrieve paginated chat transcripts. Each chat record includes the visitor's name and email, the agent who handled it, all messages in the conversation, and the customer rating if provided. Results are paginated at 150 records per page.

What is the difference between the LiveChat v2 and v3 APIs?

LiveChat v2 (api.livechatinc.com/v2) covers chat transcripts, agents, and reports β€” the core data access layer. LiveChat v3 (api.livechatinc.com/v3) is the Configuration API that controls routing, groups, chat routing rules, and real-time agent availability. Both use the same Basic Auth credentials and are available to all paying plans.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation β€” no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.