Skip to main content
RapidDev - Software Development Agency
bolt-ai-integrationsBolt Chat + API Route

How to Integrate Bolt.new with LiveChat

To integrate LiveChat with Bolt.new, add the LiveChat tracking code (a small JavaScript snippet) to your app's HTML — this works immediately in the WebContainer preview. For advanced features like fetching chat history, managing agents, or pulling analytics, create a Next.js API route that calls LiveChat's REST API using your API key and account ID stored in environment variables.

What you'll learn

  • How to get your LiveChat license number and embed the chat widget in a Bolt.new app
  • How to customize the LiveChat widget appearance and set visitor information programmatically
  • How to create a Next.js API route that fetches chat history and agent data from the LiveChat REST API
  • How to build a simple analytics dashboard showing chat volume, response times, and satisfaction scores
  • Why incoming webhook events require a deployed URL and how to configure them after deploying to Netlify or Bolt Cloud
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate15 min read15 minutesCommunicationApril 2026RapidDev Engineering Team
TL;DR

To integrate LiveChat with Bolt.new, add the LiveChat tracking code (a small JavaScript snippet) to your app's HTML — this works immediately in the WebContainer preview. For advanced features like fetching chat history, managing agents, or pulling analytics, create a Next.js API route that calls LiveChat's REST API using your API key and account ID stored in environment variables.

Adding Live Chat Support to Bolt.new Apps with LiveChat

LiveChat is one of the most straightforward customer support tools to integrate with Bolt.new because the primary integration path — embedding the chat widget — requires nothing more than adding a JavaScript snippet to your app's HTML. Unlike APIs that require OAuth flows, webhook configuration, or server-side setup, the LiveChat widget loads via a script tag, initializes itself using your license number, and appears as a chat bubble in the bottom corner of your app. This script-based embed works fully in Bolt's WebContainer preview, so you can see the chat widget immediately without deploying.

Beyond the basic widget, LiveChat provides a comprehensive REST API for accessing conversation history, managing agents, reading customer data, and building custom dashboards from chat analytics. These REST API calls require authentication using your LiveChat account email and API key, which must be kept server-side in environment variables. A Next.js API route in your Bolt project acts as the secure proxy between your frontend dashboard and LiveChat's API, keeping credentials out of the client bundle.

One important distinction: the chat widget itself is event-driven. If you want to respond to events like when a visitor starts a chat, sends a message, or rates a conversation, LiveChat provides webhooks that POST to your server when these events occur. Like all webhook-based integrations in Bolt, this inbound traffic cannot reach the WebContainer preview — you'll need to deploy to Netlify or Bolt Cloud first, then configure your webhook URL in the LiveChat developer console.

Integration method

Bolt Chat + API Route

LiveChat integrates with Bolt.new in two layers: a JavaScript widget snippet that embeds the chat window directly into your app (works immediately in the Bolt preview), and a REST API for accessing chat history, contacts, and analytics through a Next.js API route. The widget embed is the primary integration path and requires only your LiveChat license number. REST API access for advanced features requires a LiveChat developer account and API key stored securely in server-side environment variables.

Prerequisites

  • A LiveChat account (14-day free trial available, paid plans start at $20/agent/month)
  • Your LiveChat license number (found in Settings → Chat widget → Installation in the LiveChat dashboard)
  • A LiveChat API key for REST API access (generate in Settings → Integrations → API → API Keys)
  • A Bolt.new project using Next.js for server-side API routes
  • For webhook events: a deployed URL from Netlify or Bolt Cloud (webhooks cannot reach the WebContainer preview)

Step-by-step guide

1

Get Your LiveChat License Number and API Credentials

Before writing any code, you need two sets of credentials from LiveChat. The first is your license number, which identifies your LiveChat account and is used by the JavaScript widget snippet — this is a public identifier and safe to expose in client-side code (it has no write permissions). Log into your LiveChat account, go to Settings → Chat widget → Installation. You'll see the tracking code snippet, and your license number appears as a string of digits in that snippet (look for 'window.__lc.license'). Copy this number. The second credential set is for REST API access. Go to Settings → Integrations → API → API Keys and click 'Create new API key'. Give it a name like 'Bolt App'. The key is shown once — copy it immediately. You'll also need your account email (the email you use to log into LiveChat). These two values together (email + API key) form the Basic Auth credentials for all REST API requests. Keep the API key in server-side environment variables only — it provides read and write access to your entire LiveChat account data.

Pro tip: Your LiveChat license number is safe to use as a public environment variable (NEXT_PUBLIC_ prefix in Next.js) because it only identifies your account — it cannot be used to access or modify data without the API key.

Expected result: You have your LiveChat license number (a string of digits), your account email, and your API key saved for configuration.

2

Embed the LiveChat Widget in Your App

The LiveChat widget is embedded by adding a JavaScript snippet to your app's HTML. In a Next.js Bolt project, the best place is in the root layout file so the widget appears on every page. LiveChat provides a React-friendly way to load the script using the next/script component, which handles async loading without blocking page render. The widget loads from LiveChat's CDN and initializes using your license number. Once loaded, the window.__lc object is available for programmatic control. The basic embed works in Bolt's WebContainer preview immediately — you'll see the chat bubble appear in the bottom-right corner of your preview window. You can interact with it, test the chat interface, and even receive messages in your LiveChat agent console while developing. To identify logged-in users to agents, call window.LC_API after the widget loads, passing the user's name and email. This way, agents always know who they're speaking with before the conversation starts, which dramatically improves response quality.

Bolt.new Prompt

Add the LiveChat chat widget to my app. In app/layout.tsx, use next/script to load the LiveChat tracking code asynchronously using my license number from process.env.NEXT_PUBLIC_LIVECHAT_LICENSE_NUMBER. The widget should appear on every page. Also create a LiveChatIdentify client component that accepts name and email props and calls window.LC_API.set_visitor_name() and window.LC_API.set_custom_variables() to identify logged-in users to agents.

Paste this in Bolt.new chat

components/LiveChatWidget.tsx
1// app/layout.tsx additions
2import Script from 'next/script';
3
4// Add inside <body> before closing tag:
5// <LiveChatWidget licenseNumber={process.env.NEXT_PUBLIC_LIVECHAT_LICENSE_NUMBER!} />
6
7// components/LiveChatWidget.tsx
8'use client';
9import Script from 'next/script';
10
11interface LiveChatWidgetProps {
12 licenseNumber: string;
13}
14
15export function LiveChatWidget({ licenseNumber }: LiveChatWidgetProps) {
16 return (
17 <Script
18 id="livechat-widget"
19 strategy="afterInteractive"
20 dangerouslySetInnerHTML={{
21 __html: `
22 window.__lc = window.__lc || {};
23 window.__lc.license = ${licenseNumber};
24 (function(n,t,c){
25 function i(n){return e._h?e._h.apply(null,n):e._q.push(n)}
26 var e={_q:[],_h:null,_v:"2.0",on:function(){i(["on",c.call(arguments)])},
27 once:function(){i(["once",c.call(arguments)])},
28 off:function(){i(["off",c.call(arguments)])},
29 get:function(){if(!e._h)throw new Error("[LiveChatWidget] You can't use getters before load.");return i(["get",c.call(arguments)])},
30 call:function(){i(["call",c.call(arguments)])},
31 init:function(){var n=t.createElement("script");n.async=!0;
32 n.type="text/javascript";n.src="https://cdn.livechatinc.com/tracking.js";
33 t.head.appendChild(n)}};
34 !n.__lc.asyncInit&&e.init();n.LiveChatWidget=n.LiveChatWidget||e
35 }(window,document,[].slice))
36 `,
37 }}
38 />
39 );
40}

Pro tip: Use next/script with strategy='afterInteractive' so the LiveChat widget loads after React hydration. Using 'beforeInteractive' can cause hydration mismatches in Next.js.

Expected result: The LiveChat chat bubble appears in the bottom-right corner of your Bolt preview. Opening it shows a chat window where visitors can type messages. You can receive these messages in your LiveChat agent console.

3

Configure Environment Variables and Create the API Route

For REST API access, you need to store your LiveChat credentials securely and create a server-side proxy route. LiveChat's REST API uses HTTP Basic Auth where the username is your account email and the password is your API key. In Next.js, environment variables without the NEXT_PUBLIC_ prefix are only accessible server-side, which is exactly what you want for API keys. Never expose your LiveChat API key in client-side code — it would give anyone who views your source code read and write access to your entire LiveChat account, including all chat transcripts, agent accounts, and settings. Create a centralized API route that handles all LiveChat REST API calls. The route accepts a query parameter specifying which endpoint to call, builds the Basic Auth header from environment variables, and proxies the request to LiveChat's API. This pattern keeps all LiveChat API logic in one place and makes it easy to add caching or rate limiting later.

Bolt.new Prompt

Create a .env file with NEXT_PUBLIC_LIVECHAT_LICENSE_NUMBER (your public license number), LIVECHAT_ACCOUNT_ID (your email address), and LIVECHAT_API_KEY. Then create a Next.js API route at /api/livechat/[endpoint]/route.ts that accepts GET requests and proxies them to LiveChat's REST API at https://api.livechatinc.com/v3.5/[endpoint]. Use Basic auth with LIVECHAT_ACCOUNT_ID as username and LIVECHAT_API_KEY as password, and set the X-API-Version header to 3.5.

Paste this in Bolt.new chat

app/api/livechat/reports/route.ts
1// .env
2NEXT_PUBLIC_LIVECHAT_LICENSE_NUMBER=12345678
3LIVECHAT_ACCOUNT_ID=your@email.com
4LIVECHAT_API_KEY=your_api_key_here
5
6// app/api/livechat/reports/route.ts
7import { NextResponse } from 'next/server';
8
9export async function GET(request: Request) {
10 const { searchParams } = new URL(request.url);
11 const dateFrom = searchParams.get('dateFrom') || getDefaultDateFrom();
12 const dateTo = searchParams.get('dateTo') || new Date().toISOString().split('T')[0];
13
14 const accountId = process.env.LIVECHAT_ACCOUNT_ID!;
15 const apiKey = process.env.LIVECHAT_API_KEY!;
16 const basicAuth = Buffer.from(`${accountId}:${apiKey}`).toString('base64');
17
18 try {
19 const response = await fetch(
20 `https://api.livechatinc.com/v3.5/reports/chats/total-chats?from=${dateFrom}&to=${dateTo}`,
21 {
22 headers: {
23 Authorization: `Basic ${basicAuth}`,
24 'X-API-Version': '3.5',
25 'Content-Type': 'application/json',
26 },
27 }
28 );
29
30 if (!response.ok) {
31 const error = await response.json();
32 return NextResponse.json({ error }, { status: response.status });
33 }
34
35 const data = await response.json();
36 return NextResponse.json(data);
37 } catch (error: unknown) {
38 const e = error as { message: string };
39 return NextResponse.json({ error: e.message }, { status: 500 });
40 }
41}
42
43function getDefaultDateFrom() {
44 const d = new Date();
45 d.setDate(d.getDate() - 30);
46 return d.toISOString().split('T')[0];
47}

Pro tip: LiveChat's API versioning uses the X-API-Version header. Always include version 3.5 (current stable) to avoid breaking changes when LiveChat releases new versions.

Expected result: GET to /api/livechat/reports returns chat volume data from LiveChat. The API key is never exposed to the client. The .env file has all three environment variables configured.

4

Build the Analytics Dashboard UI

With the API route in place, you can build a dashboard that surfaces LiveChat data in your Bolt app. The analytics dashboard is a good starting point because it's read-only — you're fetching metrics and displaying them, which is lower risk than write operations. LiveChat's Reports API provides endpoints for total chats, chat duration, first response time, and customer satisfaction ratings (CSAT). A practical dashboard shows these four metrics as stat cards at the top, followed by a list of recent conversations. Each conversation record includes the agent who handled it, the duration, the customer's rating (if provided), and a timestamp. Use React hooks to fetch the data client-side after the dashboard mounts, showing a loading skeleton while the API route fetches from LiveChat. Add date range filter controls so users can view metrics for different time periods. Remember that all LiveChat API calls go through your Next.js API route — never call LiveChat's API directly from client components, as that would require exposing your API key.

Bolt.new Prompt

Create an analytics dashboard page at /admin/livechat. Show four metric cards at the top: Total Chats (last 30 days), Average Chat Duration (in minutes), First Response Time (in seconds), and Customer Satisfaction Score (as a percentage). Fetch each metric from the corresponding /api/livechat/reports endpoint. Below the cards, show a table of recent chats fetched from /api/livechat/chats with columns for Date, Agent Name, Duration, and Rating (show star icons for the satisfaction score). Add a date range selector at the top that updates all metrics when changed.

Paste this in Bolt.new chat

Pro tip: LiveChat's CSAT scores are optional — customers can skip rating a conversation. Filter out null ratings before calculating the average satisfaction score to avoid skewed metrics.

Expected result: The /admin/livechat dashboard loads with real data from your LiveChat account. Metric cards show actual counts. The recent chats table displays conversation records with agent names and ratings.

5

Deploy and Configure Webhooks for Real-Time Events

The widget embed and REST API polling work in Bolt's WebContainer preview. However, if you want real-time notifications when chat events occur — a new chat starts, an agent goes offline, a customer rates a conversation — you need webhooks. LiveChat sends POST requests to a URL you configure in your developer console whenever these events fire. Since Bolt's WebContainer runs inside a browser tab with no publicly accessible URL, LiveChat cannot deliver webhook payloads during development. Deploy your app to Netlify or Bolt Cloud first. After deploying, go to your LiveChat developer console (developers.livechat.com), create or select your app, go to the Webhooks section, and add a new webhook. Set the URL to your deployed endpoint (e.g., https://your-app.netlify.app/api/livechat/webhook) and select the events you want to receive (chat_created, chat_deactivated, event_created are the most useful). In your webhook handler route, you'll receive JSON payloads describing the event. Create the handler to process these events — for example, saving new chat events to your database, sending Slack notifications when chats start, or triggering email follow-ups when chats end with low satisfaction scores.

Bolt.new Prompt

Create a webhook handler at /api/livechat/webhook that receives POST requests from LiveChat. Parse the JSON payload and handle three event types: 'incoming_chat' (log new chat started with visitor info), 'chat_deactivated' (log chat ended with duration), and 'post_chat_survey_filled' (save the customer satisfaction rating to the database). Respond with 200 status for all valid payloads. Log unrecognized event types without throwing an error.

Paste this in Bolt.new chat

app/api/livechat/webhook/route.ts
1// app/api/livechat/webhook/route.ts
2import { NextResponse } from 'next/server';
3
4interface LiveChatWebhookPayload {
5 event_type: string;
6 chat?: {
7 id: string;
8 users: Array<{ id: string; name: string; email?: string; type: string }>;
9 };
10 rating?: { score: number; comment: string };
11}
12
13export async function POST(request: Request) {
14 try {
15 const payload: LiveChatWebhookPayload = await request.json();
16
17 switch (payload.event_type) {
18 case 'incoming_chat':
19 console.log('New chat started:', payload.chat?.id);
20 // Add your database write here
21 break;
22
23 case 'chat_deactivated':
24 console.log('Chat ended:', payload.chat?.id);
25 // Update chat record in database
26 break;
27
28 case 'post_chat_survey_filled':
29 console.log('Rating received:', payload.rating?.score);
30 // Save CSAT score to database
31 break;
32
33 default:
34 console.log('Unhandled event type:', payload.event_type);
35 }
36
37 return NextResponse.json({ received: true });
38 } catch (error: unknown) {
39 const e = error as { message: string };
40 return NextResponse.json({ error: e.message }, { status: 500 });
41 }
42}

Pro tip: LiveChat webhooks include a secret token you can configure in the developer console. Validate this token in your webhook handler to ensure events come from LiveChat and not from unauthorized sources.

Expected result: After deploying and configuring the webhook URL in LiveChat's developer console, new chat events trigger your webhook handler. Events are logged and processed. The LiveChat developer console shows successful webhook deliveries with 200 responses.

Common use cases

Embedded Support Chat with Visitor Identification

Add a LiveChat widget to your Bolt app and pass authenticated user data (name, email, user ID) to LiveChat so agents see who they're talking to before the conversation starts. This eliminates the need for visitors to re-enter their contact information and allows agents to pull up account history immediately.

Bolt.new Prompt

Add the LiveChat chat widget to my app. Embed the LiveChat tracking code in my root layout using my license number from the NEXT_PUBLIC_LIVECHAT_LICENSE_NUMBER environment variable. After the user logs in, use the LiveChat JavaScript API to identify the user by passing their name, email, and user ID so the agent can see who they are. Show a custom greeting message: 'Hi {firstName}! Need help? Chat with us.'

Copy this prompt to try it in Bolt.new

Custom Chat Analytics Dashboard

Build an internal admin dashboard that pulls LiveChat data — total chats, average response time, customer satisfaction scores, busiest hours — from the LiveChat REST API. Display the metrics as charts and tables so your support team can monitor performance without leaving your app.

Bolt.new Prompt

Create an admin dashboard page at /admin/chat-analytics that fetches LiveChat data through a Next.js API route at /api/livechat/reports. The API route should call LiveChat's Reports API with my LIVECHAT_ACCOUNT_ID and LIVECHAT_API_KEY to fetch the total chats count, average chat duration, and customer satisfaction score for the past 30 days. Display the three metrics as stat cards at the top, then show a table of recent chats with agent name, duration, and satisfaction rating.

Copy this prompt to try it in Bolt.new

Chat History Viewer for Support Agents

Create an internal tool that lets your support team search through past LiveChat conversations by customer email or date range. The tool fetches transcripts from LiveChat's REST API and displays them in a readable format, useful for reviewing resolved cases or training new agents.

Bolt.new Prompt

Build a chat history search page at /admin/chat-history. Add a search form with an email address field and a date range picker. On submit, call /api/livechat/chats which fetches chats from LiveChat's Chats API filtered by the provided email and date range using LIVECHAT_ACCOUNT_ID and LIVECHAT_API_KEY. Display results as an expandable list — show chat date, agent, duration, and satisfaction rating. Clicking a chat expands the full transcript.

Copy this prompt to try it in Bolt.new

Troubleshooting

LiveChat widget doesn't appear in the Bolt preview or on the deployed site

Cause: The most common cause is an incorrect license number. The widget silently fails to initialize if the license number is wrong, missing, or has extra whitespace.

Solution: Open browser DevTools (F12) → Console and look for LiveChat errors. Verify that window.__lc.license equals your actual license number by typing it in the console. Double-check the NEXT_PUBLIC_LIVECHAT_LICENSE_NUMBER environment variable in your .env file — the value should be digits only, no quotes, no spaces. Also ensure the script loads using strategy='afterInteractive' in next/script.

typescript
1// Debug in browser console:
2console.log('LC license:', window.__lc?.license);
3console.log('LiveChatWidget loaded:', typeof window.LiveChatWidget);

LiveChat REST API returns 401 Unauthorized

Cause: Basic Auth credentials are wrong. The username must be your LiveChat account email (not your agent name), and the password must be the API key (not your login password). The Base64 encoding of 'email:apikey' must be exact.

Solution: Verify LIVECHAT_ACCOUNT_ID contains your email address, not a username or account ID number. Confirm LIVECHAT_API_KEY is the key generated under Settings → Integrations → API → API Keys. Test the credentials with curl: curl -u 'your@email.com:your_api_key' 'https://api.livechatinc.com/v3.5/reports/chats/total-chats?from=2024-01-01&to=2024-01-31'

Webhooks from LiveChat never arrive during development

Cause: This is a fundamental WebContainer limitation. Bolt's runtime runs inside a browser tab with no publicly accessible URL. LiveChat's servers cannot reach the WebContainer to deliver webhook payloads.

Solution: Deploy your app to Netlify or Bolt Cloud first. After deployment, go to your LiveChat developer app settings, navigate to the Webhooks section, and configure the webhook URL to point to your deployed endpoint (e.g., https://your-app.netlify.app/api/livechat/webhook). Webhooks will work reliably once the app has a public URL.

Chat widget shows but visitor identification (name/email) doesn't work

Cause: The LiveChat JavaScript API (window.LC_API) is only available after the widget fully loads, not immediately after the script tag executes. Calling set_visitor_name() too early results in a silent failure.

Solution: Use LiveChat's event system to wait for the widget to be ready before setting visitor data. Listen for the on_after_load event, then set visitor info.

typescript
1// Wait for LiveChat to fully load before identifying the visitor
2declare global { interface Window { LC_API?: { set_visitor_name: (name: string) => void; on_after_load?: () => void; } } }
3
4if (typeof window !== 'undefined') {
5 window.LiveChatWidget?.on('ready', () => {
6 window.LiveChatWidget?.call('set_customer_name', userName);
7 window.LiveChatWidget?.call('set_customer_email', userEmail);
8 });
9}

Best practices

  • Store LIVECHAT_API_KEY as a server-side environment variable (no NEXT_PUBLIC_ prefix) — it grants access to all your chat history, agent accounts, and settings
  • Use next/script with strategy='afterInteractive' for the LiveChat widget to prevent blocking page hydration and avoid SSR conflicts
  • Proxy all LiveChat REST API calls through a Next.js API route rather than calling LiveChat's API directly from client components
  • Configure the LiveChat widget to identify authenticated users (name and email) so agents always know who they're talking to before the conversation begins
  • Test the widget embed in Bolt's WebContainer preview, but deploy to Netlify or Bolt Cloud before testing webhooks and real-time event handling
  • Respond to LiveChat webhooks with a 200 status immediately, even if your processing fails — LiveChat retries failed webhooks aggressively and slow responses trigger retries
  • Use the LiveChat visitor greeting API to customize welcome messages for different pages, for example a different message on your pricing page versus your support page
  • Monitor your LiveChat API usage — the free plan and lower tiers have rate limits on the Reports API, so avoid fetching analytics on every page load

Alternatives

Frequently asked questions

Does the LiveChat widget work in Bolt's WebContainer preview?

Yes. The LiveChat widget is a JavaScript snippet that loads from LiveChat's CDN — it works in Bolt's WebContainer preview exactly like it does on any website. You can see the chat bubble, open the chat window, and send test messages during development. The only limitation is webhooks: incoming events from LiveChat (new chat started, chat ended, rating received) require a deployed URL and won't reach the WebContainer.

How do I get my LiveChat license number?

Log into your LiveChat account at app.livechatinc.com, go to Settings → Chat widget → Installation. Your license number is the sequence of digits shown in the JavaScript snippet — look for 'window.__lc.license = XXXXXXXX'. You can also find it in Settings → Account → Account details. The license number is safe to expose in client-side code (it only identifies your account, it cannot access data).

Can I test LiveChat during development without a paid plan?

LiveChat offers a 14-day free trial with full feature access. During the trial you can embed the widget, test the chat interface, and access the REST API. After the trial, a paid plan is required (starting at $20/agent/month for the Starter plan). For development and testing purposes, the trial period is sufficient to build and validate your integration before committing to a plan.

How do I pass user data to LiveChat so agents see who they're chatting with?

After the LiveChat widget loads, use the LiveChatWidget JavaScript API to set visitor information. Call window.LiveChatWidget.call('set_customer_name', userName) and window.LiveChatWidget.call('set_customer_email', userEmail) in a useEffect hook that runs after the user logs in. Listen for the 'ready' event first to ensure the widget has fully loaded before calling these methods.

What's the difference between the LiveChat widget and the LiveChat REST API?

The widget is the chat window that appears on your site — it's embedded via a JavaScript snippet and handles all visitor-facing chat interactions. The REST API is for backend operations: reading chat transcripts, managing agents, fetching analytics reports, and responding to events. The widget embed is all most apps need; the REST API is for building custom admin dashboards, analytics tools, or automating agent management.

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.