# How to Integrate Bolt.new with LiveChat

- Tool: Bolt.new
- Difficulty: Intermediate
- Time required: 15 minutes
- Last updated: April 2026

## 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.

## Before you start

- 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.

**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.

```
// app/layout.tsx additions
import Script from 'next/script';

// Add inside <body> before closing tag:
// <LiveChatWidget licenseNumber={process.env.NEXT_PUBLIC_LIVECHAT_LICENSE_NUMBER!} />

// components/LiveChatWidget.tsx
'use client';
import Script from 'next/script';

interface LiveChatWidgetProps {
  licenseNumber: string;
}

export function LiveChatWidget({ licenseNumber }: LiveChatWidgetProps) {
  return (
    <Script
      id="livechat-widget"
      strategy="afterInteractive"
      dangerouslySetInnerHTML={{
        __html: `
          window.__lc = window.__lc || {};
          window.__lc.license = ${licenseNumber};
          (function(n,t,c){
            function i(n){return e._h?e._h.apply(null,n):e._q.push(n)}
            var e={_q:[],_h:null,_v:"2.0",on:function(){i(["on",c.call(arguments)])},
            once:function(){i(["once",c.call(arguments)])},
            off:function(){i(["off",c.call(arguments)])},
            get:function(){if(!e._h)throw new Error("[LiveChatWidget] You can't use getters before load.");return i(["get",c.call(arguments)])},
            call:function(){i(["call",c.call(arguments)])},
            init:function(){var n=t.createElement("script");n.async=!0;
            n.type="text/javascript";n.src="https://cdn.livechatinc.com/tracking.js";
            t.head.appendChild(n)}};
            !n.__lc.asyncInit&&e.init();n.LiveChatWidget=n.LiveChatWidget||e
          }(window,document,[].slice))
        `,
      }}
    />
  );
}
```

**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.

```
// .env
NEXT_PUBLIC_LIVECHAT_LICENSE_NUMBER=12345678
LIVECHAT_ACCOUNT_ID=your@email.com
LIVECHAT_API_KEY=your_api_key_here

// app/api/livechat/reports/route.ts
import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const dateFrom = searchParams.get('dateFrom') || getDefaultDateFrom();
  const dateTo = searchParams.get('dateTo') || new Date().toISOString().split('T')[0];

  const accountId = process.env.LIVECHAT_ACCOUNT_ID!;
  const apiKey = process.env.LIVECHAT_API_KEY!;
  const basicAuth = Buffer.from(`${accountId}:${apiKey}`).toString('base64');

  try {
    const response = await fetch(
      `https://api.livechatinc.com/v3.5/reports/chats/total-chats?from=${dateFrom}&to=${dateTo}`,
      {
        headers: {
          Authorization: `Basic ${basicAuth}`,
          'X-API-Version': '3.5',
          'Content-Type': 'application/json',
        },
      }
    );

    if (!response.ok) {
      const error = await response.json();
      return NextResponse.json({ error }, { status: response.status });
    }

    const data = await response.json();
    return NextResponse.json(data);
  } catch (error: unknown) {
    const e = error as { message: string };
    return NextResponse.json({ error: e.message }, { status: 500 });
  }
}

function getDefaultDateFrom() {
  const d = new Date();
  d.setDate(d.getDate() - 30);
  return d.toISOString().split('T')[0];
}
```

**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.

**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.

```
// app/api/livechat/webhook/route.ts
import { NextResponse } from 'next/server';

interface LiveChatWebhookPayload {
  event_type: string;
  chat?: {
    id: string;
    users: Array<{ id: string; name: string; email?: string; type: string }>;
  };
  rating?: { score: number; comment: string };
}

export async function POST(request: Request) {
  try {
    const payload: LiveChatWebhookPayload = await request.json();

    switch (payload.event_type) {
      case 'incoming_chat':
        console.log('New chat started:', payload.chat?.id);
        // Add your database write here
        break;

      case 'chat_deactivated':
        console.log('Chat ended:', payload.chat?.id);
        // Update chat record in database
        break;

      case 'post_chat_survey_filled':
        console.log('Rating received:', payload.rating?.score);
        // Save CSAT score to database
        break;

      default:
        console.log('Unhandled event type:', payload.event_type);
    }

    return NextResponse.json({ received: true });
  } catch (error: unknown) {
    const e = error as { message: string };
    return NextResponse.json({ error: e.message }, { status: 500 });
  }
}
```

**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.

## 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

## 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.

Prompt example:

```
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.'
```

### 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.

Prompt example:

```
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.
```

### 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.

Prompt example:

```
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.
```

## 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.

```
// Debug in browser console:
console.log('LC license:', window.__lc?.license);
console.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.

```
// Wait for LiveChat to fully load before identifying the visitor
declare global { interface Window { LC_API?: { set_visitor_name: (name: string) => void; on_after_load?: () => void; } } }

if (typeof window !== 'undefined') {
  window.LiveChatWidget?.on('ready', () => {
    window.LiveChatWidget?.call('set_customer_name', userName);
    window.LiveChatWidget?.call('set_customer_email', userEmail);
  });
}
```

## 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.

---

Source: https://www.rapidevelopers.com/bolt-ai-integrations/livechat
© RapidDev — https://www.rapidevelopers.com/bolt-ai-integrations/livechat
