Skip to content
المشاريع

حول

Open-source live chat for Rails: drop-in support widget + team inbox, in your own database. Alternative to Crisp, Intercom, Chatwoot — inside your Rails app, not another service.

البيانات والتحليلات

كيف تُقاس هذه الأرقام

النمو المقاس للنجوم

خلال 24 ساعة
٠
خلال 7 أيام
٠
خلال 15 يومًا
٠
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

livechat

Gem Version Downloads CI License: MIT

In-app support messaging for Rails. Add a chat button so users can ask for help from the page where they got stuck. Your team answers from a mounted inbox. No SaaS account, no third-party script, no separate app, no customer data leaving your database.

Use it when email is too detached, Intercom is too much, and Chatwoot is another app you do not want to deploy.

The livechat widget open over a running Rails app

Install

# Gemfile
gem "livechat"
bundle install
bin/rails generate livechat:install
bin/rails db:migrate
<%# app/views/layouts/application.html.erb %>
<%= livechat_tag %>

That's it. Visit any page, click the bubble, say hi. Answer yourself at /livechat.

Optional demo data:

bin/rails livechat:seed_demo

It creates two idempotent sample conversations: one open thread with an unread visitor reply, and one resolved thread. Running the task again refreshes those demo messages instead of duplicating conversations.

[!IMPORTANT] The inbox defaults to development only. Set authorize_agent before you deploy — see Configure.

Ruby >= 3.2 · Rails >= 7.1, < 9 · Active Storage only if you want file attachments.

Installing with a coding agent? Point it at AGENTS.md — the same steps in the order an agent needs them, plus the gates it tends to get wrong and the things it should not do. It ships inside the gem, so cat "$(bundle show livechat)/AGENTS.md" works from any app that bundles it.

What you get

Widget Chat bubble, expandable panel, drafts preserved, unread badges
Chat page The same chat as a page with a URL — for your nav and the reply email
Inbox Open / resolved tabs, search across everything, who-worked-what column
Team Any teammate answers any thread; every reply signed with its author
Email Both directions — one per unread stretch, not one per message
Files Images inline, documents as links. Served through the engine, never a blob URL
Realtime Polling by default (no Redis, no Action Cable). Push is opt-in
Threads One per visitor — a conversation, not tickets. Writing again reopens it
Deps None. Plain JS — no Tailwind, no Stimulus, no importmap, no build step
Auth Lambdas over the raw request — Devise, Rails 8 auth, anything
i18n 27 languages, RTL included
Turbo/CSP Turbo Drive and strict nonce-based CSP out of the box

Why a gem

livechat Hosted chat SaaS
Cost Free, MIT Per-seat, per-month
Where conversations live Your database The vendor's
To deploy bundle add livechat A script tag, or a second app
Visitor identity Server-side, from your session Whatever the visitor types
Page weight One <script>, no CDN Third-party bundle
Infrastructure None. Polling by default Theirs, or your own Redis + Cable
"Powered by" badge Never Usually, until you pay

How it works

  1. Add <%= livechat_tag %> to your layout. A bubble appears bottom-right — or open the panel from any element with data-livechat-open, or window.Livechat.open().
  2. A visitor writes. The message lands in livechat_conversations in your database, and — if you configured it — in your team's email.
  3. Your team answers at /livechat. Several people can work the same thread; resolve it when done. A visitor writing again reopens it.
  4. The visitor sees the reply in the widget, or by email when they're gone.

Each visitor has one ongoing conversation. Resolving it marks the current exchange as handled; the visitor can send another message at any time to reopen that same thread, with the history intact. Different questions share one open/resolved status.

Realtime is polling, on purpose: ~4s while the panel is open, ~30s in the background, nothing at all for visitors who never wrote. No Action Cable, no Redis, no infrastructure. At support-chat volume you will not notice; your ops person will notice there is nothing new to run. Already running Action Cable and want instant delivery? config.action_cable = true — polling stays the fallback.

The inbox

Open and resolved filters, unread badges, search (visitor name, email, and everything anyone wrote), and a two-column desktop layout with the chat list on the left and the selected thread on the right. Reply with Cmd/Ctrl+Enter, resolve, reopen. The inbox keeps itself fresh while you watch — and never reloads over a half-written reply or search. A thread that came from a site other than the inbox's own host carries that site's name, and the list narrows to one site at a time, for an app that embeds the widget on several sites.

Desktop inbox Mobile thread
The inbox: conversation list on the left and selected thread on the right The mobile thread view with reply composer

Every reply carries its author and time, and resolving is recorded in the thread. Gated by authorize_agent.

Writing first

An agent can start the conversation with a signed-in user who never wrote. Tell the gem how to look a user up, then link to the page from your own admin:

config.find_visitor = ->(id) { User.find_by(id: id) }
<%= link_to "Message in chat", Livechat.new_conversation_path(user) %>

The page opens the user's thread if they have one. If they don't, it shows a composer, and the thread starts with the first message sent. The user sees it in the widget (with the unread badge) on their next visit. If they have an email and mailer_from is set, they also get the usual email, worded "sent you a message" instead of "replied". Guests can't be written to: a cookie isn't someone you can look up.

This is for service messages to one person, not campaigns. It sends email to people who never wrote, so return nil from find_visitor for anyone your team must not contact, and keep marketing out of it.

Configure

Everything is optional — a fresh install works with zero config. In config/initializers/livechat.rb:

Option Default What it does
authorize_agent development only Who can read the inbox. Override before deploying
base_controller_class ActionController::Base Controller the inbox inherits — name your admin's and it adopts its layout, helpers and auth
enabled everyone Who sees the widget. false hides it and rejects posts
current_user nil Identify the visitor. Receives the request
find_visitor nil (off) Look a user up by id so an agent can write first. Receives the id as a String
app_name Rails app name Shown in the widget header
greeting localized default First message visitors see
reply_time_text localized default "We usually reply within a few hours"
launcher_label localized default Text on the bubble
avatar_url nil Customer-facing avatar in the widget header; URL or per-request callable
accent_color nil One hex restyles launcher, header, bubbles, send button
show_launcher true false hides the bubble — bring your own entry point
allowed_embed_origins [] Origins allowed to embed the widget on a page this app doesn't render
visitor_label name, else email How a visitor is labelled in the inbox
agent_label name, else email How an agent is labelled internally
agent_display_name the full label What visitors see — trim it or anonymise it
mailer_from nil Required for any email
agent_emails nil Who gets notified of new visitor messages
on_visitor_message no-op Runs after a visitor writes — Slack, etc.
on_agent_message no-op Runs after an agent replies
attach_files true File attachments (needs Active Storage)
storage_service nil Named Active Storage service for chat attachments
max_attachments 5 Per message
max_attachment_size 10.megabytes Enforced server-side
allowed_attachment_types nil (any) Or an allowlist, e.g. %w[image/png application/pdf]
action_cable false Opt into push delivery
action_cable_url "/cable" Match your mount ActionCable...
rate_limit { to: 30, within: 1.minute } Per-IP throttle (Rails 7.2+). nil disables
chat_path <mount_path>/chat The chat as a page. A path of your own, false for none, or a callable receiving the request — see The chat as a page
guest_cookie_expires_in nil (20 years) Lifetime of a guest's livechat_vid cookie, counted from their latest message, e.g. 13.months
mount_path "/livechat" Keep in sync with mount in routes.rb

A typical initializer:

Livechat.configure do |config|
  config.current_user     = ->(request) { request.env["warden"]&.user }
  config.authorize_agent  = ->(request) { request.env["warden"]&.user&.admin? }
  config.mailer_from      = "[email protected]"
  config.agent_emails     = -> { User.where(admin: true).pluck(:email) }
  config.reply_time_text  = "We usually reply within an hour."
  config.avatar_url       = "/support-avatar.png"
  config.accent_color     = "#7c3aed"
end

avatar_url, greeting, reply_time_text, launcher_label, show_launcher and accent_color each take a callable receiving the request, so one app can brand or word the widget per tenant — or per surface:

config.avatar_url = ->(request) { request.env["current_account"]&.support_avatar_url }

Prefer a same-origin image. If the URL uses another host, allow that host in your application's img-src Content Security Policy.

Gates receive the raw request, so they work with any auth:

# Devise / Warden
config.current_user = ->(request) { request.env["warden"]&.user }

# Rails 8 built-in auth (bin/rails generate authentication)
config.current_user = lambda do |request|
  token = request.cookies["session_token"]
  Session.find_signed(token)&.user if token
end
Who visitors talk to

Replies are signed. What visitors see is up to you:

config.agent_display_name = ->(label) { label.split.first }   # "Ada"
config.agent_display_name = ->(_label) { "Support team" }     # anonymous
Email, both directions

When a visitor writes and nobody has read it, the team gets one email — one per unread stretch, not one per message. When an agent replies and the visitor is away, the visitor gets one email (signed-in visitors automatically, guests once they leave an address — the widget asks, gently).

Requires mailer_from; team notifications also need agent_emails. For anything else, hook in:

config.on_visitor_message = ->(message) { SlackNotifier.ping(message) }
File attachments

On by default wherever the app has Active Storage. If you don't already:

bin/rails active_storage:install && bin/rails db:migrate

Visitors get a paperclip in the composer; agents get a file field on the reply form. Safe image formats render inline, other files as download links. Every file is served through the engine's own route and gated the same way the chat is — an agent, or the visitor who owns that conversation — so nothing leaks through a guessable or long-lived blob URL. Responses are private and no-store; audio supports byte ranges for playback and seeking.

Where Active Storage isn't installed, the widget quietly stays text-only.

Set config.storage_service to route chat uploads to a dedicated Active Storage service from your app's config/storage.yml:

config.storage_service = :livechat_uploads

On a site this app doesn't render

Marketing sites are usually static and live on their own host, which is exactly where people ask presales questions. The widget can go there too, with one tag:

<script src="/livechat/embed.js" defer></script>

embed.js carries the config block the layout helper would have rendered and pulls in the widget, so the static page never reproduces engine markup that a future release might change. Add ?locale=de for a translated site.

The proxy

The widget sends credentials: "same-origin", so it has to reach Rails on the page's own origin. A cross-origin script tag would load and then quietly fail to carry the visitor's cookie. Proxy /livechat/* from the site to Rails. Whatever does it, a CDN rule, an edge function or nginx, has to:

  • Forward everything under the mount path: every method, request bodies (messages and file uploads are POSTs) and query strings. Keep the site's own rewriting off it. Trailing-slash redirects, locale prefixes and content negotiation all break the widget's endpoints.
  • Pass cookies both ways. The guest cookie is a guest's only key to their thread. If Rails sets cookies with a Domain naming its own host (a session store with domain: :all, say), strip it, or the browser drops the cookie on the marketing origin.
  • Pass redirects through rather than following them.
  • Mark what it forwards with a header of its own, such as X-Livechat-Surface: website. A <script src> request like embed.js carries no Origin, so without a header Rails cannot tell the marketing site from the app when it builds the widget's config. See Telling the surfaces apart.
  • Forward the visitor's address, or every visitor arrives as the proxy and shares one rate-limit bucket. Setting X-Forwarded-For is not enough if a proxy in front of Rails rewrites it from the TCP peer, as kamal-proxy does unless forward_headers is on. Turning that on lets anyone who reaches Rails directly choose their own address, so weigh it for your setup. A narrower way out is below the example.
  • Never cache it. Keep /livechat/* out of any "cache everything" rule on the CDN. embed.js and the visitor API answer per visitor. The one safe exception is embed.js cached on what it varies by.

A Cloudflare Pages Function at functions/livechat/[[path]].js does all of it:

export async function onRequest({ request, env }) {
  const url = new URL(request.url)
  const headers = new Headers(request.headers)
  headers.delete("host")
  headers.set("X-Livechat-Surface", "website")
  const ip = request.headers.get("cf-connecting-ip")
  if (ip) headers.set("X-Forwarded-For", ip)

  const upstream = await fetch(`https://app.example.com${url.pathname}${url.search}`, {
    method: request.method,
    headers,
    body: ["GET", "HEAD"].includes(request.method) ? undefined : request.body,
    redirect: "manual"
  })

  const response = new Response(upstream.body, upstream)
  response.headers.delete("set-cookie")
  for (const cookie of upstream.headers.getSetCookie()) {
    response.headers.append("set-cookie", cookie.replace(/;\s*domain=[^;]*/gi, ""))
  }
  return response
}

If every visitor reaches Rails as the proxy's address, the rate limiter can key on one the proxy vouches for instead. config.rate_limit passes by: through to Rails' rate_limit. Have the proxy send the visitor's address together with a secret only it knows, and trust the address only when the secret matches:

// in the function above
headers.set("X-Livechat-Client-IP", ip)
headers.set("X-Livechat-Proxy-Secret", env.LIVECHAT_PROXY_SECRET)
config.rate_limit = {
  to: 30, within: 1.minute,
  by: lambda do
    secret = ENV.fetch("LIVECHAT_PROXY_SECRET", "")
    vouched = secret.present? &&
      ActiveSupport::SecurityUtils.secure_compare(request.headers["X-Livechat-Proxy-Secret"].to_s, secret)
    (vouched && request.headers["X-Livechat-Client-IP"].presence) || request.remote_ip
  end
}

Nothing else in the app trusts those headers, so no other limit loosens. The cost is one more secret to keep in step on both sides.

Allowlisting the origin

A static page cannot mint a CSRF token, so the embedding origin has to be allowlisted:

config.allowed_embed_origins = ["https://example.com"]

A request from a listed origin skips forgery protection. What makes that safe is that Origin is set by the browser and cannot be forged by page script, so listing an origin grants nothing to any other site; the exemption covers only the widget's visitor endpoints and never the inbox; and a request with no Origin header at all is never treated as embedded, so a non-browser client gains nothing.

Cookies

Livechat.public_paths lists the endpoints that need no Rails session: the widget script, the embed bootstrap, the visitor API and attachments. If your app touches the session on every request (a CSP nonce generator usually does), skip them there, or every visitor who merely loads a page leaves with a cookie:

config.content_security_policy_nonce_generator = lambda do |request|
  next if Livechat.public_paths.any? { |path| request.path.start_with?(path) }
  request.session[:csp_nonce] ||= SecureRandom.hex(16)
end

Done that way, a visitor gets exactly one cookie, livechat_vid (HttpOnly, SameSite=Lax), and only when they send a message. It lives 20 years unless you set config.guest_cookie_expires_in, which counts from their latest message. Match it to how long you keep threads: 13.months beside a 12-month purge_resolved, say. The chat page (<mount_path>/chat) is an HTML page with a CSRF token, so it does use the session.

The site's own Content Security Policy

If the site sends a CSP, the widget needs script-src 'self' for embed.js and widget.js, connect-src 'self' for its requests, and style-src 'unsafe-inline', because it injects its stylesheet as a <style> element. Attachments and the avatar load from the mount path, so img-src 'self' covers them.

What your privacy notice should say

A marketing site that offers chat starts collecting what visitors type, often before they are customers. Three things change for the notice:

  • The cookie: livechat_vid, set only when the visitor sends a message, with its lifetime.
  • Where messages pass: through the proxy, an edge provider in most setups, on their way to your servers.
  • How long you keep them: the engine deletes nothing by itself. Schedule Livechat::Conversation.purge_resolved(older_than: ...) in a recurring job, or the retention period you state is a claim nothing enforces.

Telling the surfaces apart

The same app now serves two audiences: buyers on the marketing site, users in the app. Write the test once and key every setting that differs on it:

# config/initializers/livechat.rb
marketing = lambda do |request|
  request.get_header("HTTP_X_LIVECHAT_SURFACE") == "website" ||
    request.origin == "https://example.com"
end

Livechat.configure do |config|
  config.allowed_embed_origins = ["https://example.com"]
  config.enabled = ->(request) { marketing.call(request) || request.env["warden"]&.user.present? }
  config.show_launcher = ->(request) { marketing.call(request) }
  config.greeting = ->(request) { "Questions before you buy? Ask away." if marketing.call(request) }
  config.chat_path = ->(request) { marketing.call(request) ? false : "/support" }
end

It needs both checks. embed.js carries only the proxy's header. The reply email has no request at all, so chat_path gets one rebuilt from the page the visitor last wrote from, with that page's Origin and none of your headers. The widget's own requests carry both.

The header decides what the widget looks like, not what it may do. Anyone can send it by hand, and all it buys them is the chat the marketing site offers everyone anyway. Whether a write is accepted rests on the browser-set Origin.

A chat page of your own (chat_path) lives on the app's host, and usually behind its sign-in, so on the marketing site the "open as a page" icon would lead nowhere. Return false there to drop the icon, and a guest's reply email links back to the page they wrote from. Return nil instead to serve the engine's page through the same proxy.

Several sites

Nothing limits the widget to one site. Ten marketing sites can all embed it and share one inbox. For each one, proxy /livechat/* to the app as above and list its origin:

config.allowed_embed_origins = %w[https://site-one.com https://site-two.com]
# or, when the list lives in your database:
config.allowed_embed_origins = ->(request) { Site.pluck(:origin) }

Have each proxy name its site in the header (X-Livechat-Surface: site-two), and turn the header or the Origin into a site to key the settings on:

SITES = {
  "site-one" => { origin: "https://site-one.com", color: "#7c3aed" },
  "site-two" => { origin: "https://site-two.com", color: "#059669" }
}.freeze

site_for = lambda do |request|
  SITES.find do |name, site|
    request.get_header("HTTP_X_LIVECHAT_SURFACE") == name || request.origin == site[:origin]
  end&.last
end

config.accent_color = ->(request) { site_for.call(request)&.dig(:color) }

What to expect with more than one:

  • A visitor is a separate guest on each site. The guest cookie belongs to the site's origin, so someone who writes on two of them has two threads.
  • The inbox labels each thread with its site: the host of the page the visitor last wrote from, shown whenever it isn't the inbox's own host.
  • The inbox filters by site. Its list offers the inbox's own host and every site in allowed_embed_origins, resolved with the inbox's request, so a callable that needs a visitor's Origin to answer leaves the filter out. A site you drop from the list stops being offered; its threads stay under "All sites".
  • A reply email links back to the site the visitor wrote from.
  • Each proxy has to forward the visitor's address. The rate limiter keys on it, and every site shares the one limiter.

What it costs per page view

  • embed.js: one request to Rails on every page view, never cached because its config is per visitor. It reaches the database only through your own enabled, current_user and settings callables, and through any middleware your app runs on every request. Don't let a CDN cache it as is: the widget trusts what it says. To take it off Rails, see the next section.
  • widget.js: fingerprinted and cached by the browser for a year.
  • The conversation check: only for a browser that has written before, or a signed-in visitor. embed.js tells the widget which, so a visitor who never wrote makes no further request.
  • Polling: every 30 seconds while a tab with a thread is visible, every 4 seconds while the panel is open, nothing while the tab is hidden.

So a visitor who never chats costs one small request per page view. Behind an edge function, every forwarded request is also an invocation, which is the number to check against your plan.

Caching embed.js at the edge

On a busy site, embed.js is the request that grows with traffic. A visitor who never chats costs nothing else. It can't be cached as it stands, because it tells the widget whether this browser has written before. But on a site where nobody signs in, that one bit is all that differs between visitors, so an edge cache keyed on it serves every visitor a correct copy:

// functions/livechat/[[path]].js: the proxy above, with its onRequest renamed
// to `async function forward(request, env)`, behind this one.
const EMBED_TTL = 60 // seconds a data center reuses one copy
// Cookies that can sign someone in on this site. Any of them skips the cache.
const SIGNED_IN = /(?:^|;\s*)_myapp_session=/

export async function onRequest(context) {
  const { request, env } = context
  const url = new URL(request.url)
  const cookie = request.headers.get("cookie") || ""
  if (request.method !== "GET" || url.pathname !== "/livechat/embed.js" || SIGNED_IN.test(cookie)) {
    return forward(request, env)
  }

  // All embed.js varies by on a site nobody signs in to: its URL, locale
  // included, and whether this browser has written before.
  const key = new URL(url)
  key.searchParams.set("livechat-wrote", /(?:^|;\s*)livechat_vid=/.test(cookie) ? "1" : "0")

  let response = await caches.default.match(key.toString())
  if (!response) {
    const upstream = await forward(request, env)
    if (!upstream.ok || upstream.headers.has("set-cookie")) return upstream
    response = new Response(upstream.body, upstream)
    response.headers.set("Cache-Control", `public, max-age=${EMBED_TTL}`)
    context.waitUntil(caches.default.put(key.toString(), response.clone()))
  }

  // The browser must not keep it: its next page view may follow a first message.
  response = new Response(response.body, response)
  response.headers.set("Cache-Control", "no-store")
  return response
}

Rails then sees about one embed.js request per minute for each combination of site, locale and "has written", in each data center that serves your visitors. Before, it saw one on every page view. The visitor API, attachments and the widget's polling still go straight through.

It is correct only while all of these hold:

  • Nobody is signed in on that site. current_user must come back nil for every request from it, and the settings callables must depend only on the site, through the proxy's header or the Origin, never on the visitor. If a cookie can sign someone in there (a session cookie shared across subdomains, say), name it in SIGNED_IN so those requests skip the cache.
  • embed.js sets no cookie. Skip the session on Livechat.public_paths as in Cookies. The function refuses to store a response that sets one anyway, so getting this wrong costs only the cache hits.
  • A minute of staleness is fine. A change to enabled or to a setting reaches visitors within EMBED_TTL, data center by data center, and so does a deploy. A cached copy still points at the old widget.js fingerprint, which Rails answers with the current code, just without the year-long cache.

The copy the browser receives stays no-store. A browser that kept its own copy would still say "never wrote" on the page after a visitor's first message, and the widget would skip the check that shows them the reply.

Local development

A static site generator's dev server (hugo server, astro dev) has no proxy, so /livechat/embed.js answers 404 locally and no bubble appears. Put a small proxy in front of it that sends /livechat/* to Rails and everything else to the dev server, or run your edge function itself with Node, and add its origin (http://localhost:4000, say) to allowed_embed_origins in development. Node's fetch wants duplex: "half" to stream a request body, which edge runtimes do not.

Browsers share cookies across ports on localhost, so locally a signed-in app session reaches the marketing site's chat too. Use a private window to see what a guest sees.

Privacy, retention, and deletion

Livechat stores conversation identity and context, message bodies and attribution, read/status timestamps, and optional attachments in the host application. Captured page URLs are limited to HTTP(S) and stored without credentials, query strings, or fragments. The engine does not send data to a Livechat service, but configured notification emails and message hooks can send message content, visitor context, and attachment filenames wherever the host chooses.

Every authorized agent can read every conversation in this one shared inbox. Visitors can read only the conversation resolved from their signed-in id or guest cookie. Livechat does not provide tenant-isolated agent inboxes in 1.x; do not use one mount for mutually isolated tenant support teams.

No record is deleted automatically. Delete one conversation (including its messages), all conversations for a user, or resolved history past a host-chosen cutoff explicitly:

Livechat::Conversation.find(id).destroy!
Livechat::Conversation.where(visitor_id: user.id.to_s).find_each(&:destroy!)
Livechat::Conversation.purge_resolved(older_than: 90.days.ago)

Use destroy!, not delete_all, when attachments must follow Rails' Active Storage lifecycle. Confirm object-storage jobs, replicas, backups, notification emails, hook destinations, logs, and exports separately: deleting live database rows cannot retract those copies. allowed_attachment_types is an upload allowlist, not malware scanning; choose a restrictive list and storage policy for your application. See SECURITY.md for the full boundary.

Realtime with Action Cable

Polling is the default and needs nothing from your app. If you already run Action Cable, turn on push so a reply appears the instant it's sent:

config.action_cable = true
config.action_cable_url = "/cable" # match your `mount ActionCable... => ...`

A new message nudges the widget and the inbox to refresh at once; polling stays the fallback, so a dropped socket or a proxy that blocks WebSockets never means a missed message. The widget speaks the Action Cable protocol over a plain WebSocket — no @rails/actioncable, no build step — and only ever subscribes to a stream the server signed for it. Under a strict CSP, allow the socket with connect-src 'self'.

Widget API

window.Livechat.open() / .close() open("Hi, I need help with…") prefills the box — never over a visitor's draft
data-livechat-open Any element opens the panel on click
data-livechat-message="…" Prefill from that element — great for contextual buttons
data-livechat-badge-class="…" Classes for that element's unread badge, in place of the built-in style
<%= livechat_button %> A plain, unstyled opener button
<%= livechat_button("Ask about this order", message: "I need help with order ##{@order.id}") %> Open and prefill in one helper
config.show_launcher = false Hide the bubble entirely
<%= livechat_chat %> The chat filling an element of your page — see below

While replies are unread, every data-livechat-open element carries a small count badge — so hiding the launcher never hides the answer.

The badge has a plain red style of its own. To match your design system, name your own classes on the opener; the built-in style then steps aside:

<button data-livechat-open data-livechat-badge-class="badge badge-error badge-xs ms-auto">
  Contact support
</button>

Contextual buttons are where a Rails app beats a generic support widget:

<%= livechat_button("Ask about this order",
      message: "I need help with order ##{@order.id}") %>

<%= livechat_button("Ask about this invoice",
      message: "I need help with invoice ##{@invoice.number}") %>

<button data-livechat-open
        data-livechat-message="I need help with project <%= @project.name %>">
  Contact support
</button>

The chat as a page

The bubble is for asking from where you are. Some visitors want the chat somewhere they can go back to — a Support link in your nav, a tab of its own, the link in the reply email. That is /livechat/chat: the visitor's conversation filling the window, the same thread the bubble opens.

<%= link_to "Support chat", Livechat.chat_path(locale: I18n.locale) %>

The engine's page doesn't run your app's locale switching, hence locale:. The panel has an icon that opens it, passing the language along by itself.

The URL is the same for everyone. Like the widget, the page finds the visitor's conversation from their signed-in id or guest cookie, never from the URL, so a forwarded link shows a stranger their own empty chat and nothing else. It also means the page shows a thread only to a browser that already carries the visitor's identity: a signed-in session, or the guest cookie of the browser they wrote from. The engine's page can't send anyone to your sign-in, so a signed-out user who opens it sees an empty chat.

That is why the reply email's "Continue the conversation" link goes to the chat page for guests, but to the last page they wrote from for signed-in visitors — your page asks them to sign in, and the thread is there after. With chat_path pointing at a page of your own (which can require sign-in), the email links that page for everyone.

The engine's page is deliberately bare: your app name, the chat, nothing of your layout. To have the chat inside your own layout and navigation, render it in a page of yours and point chat_path there — the panel's icon and the email follow, and /livechat/chat redirects to it:

<%# app/views/support/show.html.erb %>
<%= livechat_chat style: "height: 70vh" %>
config.chat_path = "/support"   # or false: no chat page, no icon

livechat_chat is only the element; the livechat_tag already in your layout fills it. Give it a height, or put it in something that has one. While it is on the page the bubble stays away, and every data-livechat-open element there moves focus into it.

Messages written on the chat page don't count as "the page they were on" for your team: the notification email and the inbox's site label keep the last page where they used the bubble.

Compatibility and public API

The following are the model and integration contracts that 1.x will keep stable under semantic versioning:

  • Livechat::Conversation, including STATUSES, TYPING_TTL, its persisted fields, messages, recent_first, for_visitor, claim!, posting and read/status methods, display_name, and purge_resolved.
  • Livechat::Message, including AUTHOR_TYPES, EVENTS, MAX_BODY_LENGTH, its persisted fields, optional files, documented scopes, author/read predicates, public_label, attached_files, and preview.
  • Livechat.configure, mount_livechat, livechat_tag, livechat_button, livechat_chat, Livechat.chat_path, Livechat.new_conversation_path, window.Livechat.open/close, data-livechat-open, and data-livechat-message.
  • The chat page under the mount path (chat), including its locale parameter, and the agent's new page with its visitor_id parameter.
  • The embed.js endpoint under the mount path, including its locale parameter. The markup it writes is private — embed the endpoint, not a copy of its output.
  • config.on_visitor_message and config.on_agent_message, each called with the saved Livechat::Message documented by the initializer.

Conversation and Message are intentionally distinct and will not become a generic Post during 1.x. Engine controllers, partials, CSS classes, generated HTML, and widget implementation objects are private. Incompatible changes to the public list above wait for a new major version; a deprecation normally ships first.

Upgrading to 1.8

Nothing to change. To let agents write first, set config.find_visitor and link to Livechat.new_conversation_path(user). A guest who signs in while their account already has a thread now has the two merged into one. The inbox names the site a thread came from when that isn't its own host.

Upgrading to 1.7

Nothing to change. config.guest_cookie_expires_in sets a lifetime for the guest cookie, renewed with every message; without it the cookie stays permanent.

Upgrading to 1.6

Nothing to change. A site embedding the widget through embed.js makes one request fewer per page view for visitors who never wrote.

Upgrading to 1.5

Nothing to change. config.chat_path now also takes a callable receiving the request, and Livechat.chat_path takes request: to resolve it in a nav link.

Upgrading to 1.4

The chat page needs nothing. One optional migration gives livechat_messages the foreign key fresh installs now create, so a bulk delete_all on conversations can no longer leave their messages behind:

bin/rails generate livechat:foreign_key && bin/rails db:migrate

On PostgreSQL it goes in without blocking writes. It fails if messages already point at a deleted conversation; the generator prints the query that finds them.

Upgrading from 0.x

There is no migration, initializer change, constant alias, or model rename. Stored page URLs become query-free on the next visitor message, attachment responses stay on the same engine URL but now stream privately instead of being buffered, and Rails 9 is excluded until a compatible release is tested.

Use cases

  • SaaS apps: answer billing, onboarding and account questions from inside the app.
  • Customer portals: let users ask about orders, invoices, documents or bookings.
  • Marketplaces: keep buyer, seller and admin support tied to the current page.
  • Internal tools: give non-technical teammates a direct line from admin screens.
  • Course and member apps: handle access, lesson and subscription questions in context.

What it doesn't do

No AI bots, no canned responses, no omnichannel (WhatsApp, Messenger…), no visitor tracking, no "powered by" badge. If you need a support platform, Chatwoot is excellent. If you need your users to be able to reach you from inside your Rails app — this is a gem's worth of exactly that.

Development

bundle exec rake test
bundle exec rake test:system
bundle exec rubocop

One family

Five Rails engines built on the same backbone, so adopting a second one is mostly muscle memory:

Gem What it does
testimonials Testimonials, reviews and NPS — text and video, collected in your own app
ideasbugs In-app bug reports and feature requests, with a triage queue
livechat (this gem) Live chat between your visitors and your agents, self-hosted
product_tours Product tours and video tutorials, shown in-app at the right moment
i18n_proofreading In-context translation fixes suggested by your own users

They share the install shape (generate <gem>:install, mount, one initializer), the same host hooks (base_controller_class to inherit your admin's controller, agent_layout for just the shell), one dashboard design system — the same two-pane layout, colour tokens and components in all five, scoped so it cannot touch your own CSS — and migrations that follow your app's primary_key_type.

Affiliation

An independent open-source Rails engine. Not affiliated with or endorsed by the company behind livechat.com.

License

MIT.

Rails edge and Ractors

Rails edge is tested alongside Rails 7.1–8.1. Experimental Ruby 4.0+ Ractor hosting requires additional upstream dependencies and freezes configuration at startup. See the Ractor hosting guide for callbacks, requirements and checks.

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…