@fstacksoftware/chatwoot-embed
v1.3.1
Published
Chatwoot widget for Shopify embedded apps: persistent session in iframe, HMAC identity, 1 conversation per shop
Readme
@fstacksoftware/chatwoot-embed
Chatwoot widget for Shopify embedded apps (Remix/React):
- Keeps the chat session alive when the app runs inside the Shopify admin iframe (cookies are blocked → shimmed via localStorage)
- Automatic identity validation (HMAC)
- Stores the session in the contact attribute
init_session→ every device of a shop shares one conversation
Installation
npm i @fstacksoftware/chatwoot-embedChatwoot setup (one time)
- Inbox (Website) → Configuration → Identity Validation → copy the HMAC token
- Inbox → Settings: enable Allow messages after conversation resolved, disable Allow users to end conversation
- Create a dedicated agent (e.g.
API Bot) → Profile → copy its Access Token (a regular agent is enough, administrator is not required) - Make the session token non-expiring:
docker compose exec rails bundle exec rails runner \ 'c=InstallationConfig.find_or_initialize_by(name:"WIDGET_TOKEN_EXPIRY"); c.value="36500"; c.locked=false; c.save!' - Optional: Inbox → Settings → disable Enable email collect box (see Duplicate emails)
ENV
CHATWOOT_BASE_URL=https://chat.example.com
CHATWOOT_WEBSITE_TOKEN=xxx
CHATWOOT_ACCOUNT_ID=1
CHATWOOT_API_TOKEN=xxx
CHATWOOT_HMAC_TOKEN=xxxUsage (Remix + Shopify)
1. Server instance — app/chatwoot.server.ts
import { createChatwootServer } from "@fstacksoftware/chatwoot-embed";
export const chatwoot = createChatwootServer({
baseUrl: process.env.CHATWOOT_BASE_URL!,
websiteToken: process.env.CHATWOOT_WEBSITE_TOKEN!,
apiToken: process.env.CHATWOOT_API_TOKEN!,
accountId: process.env.CHATWOOT_ACCOUNT_ID,
hmacToken: process.env.CHATWOOT_HMAC_TOKEN,
});2. Loader — app/root.tsx
import { chatwoot } from "./chatwoot.server";
export async function loader({ request }: LoaderFunctionArgs) {
const { session } = await authenticate.admin(request);
return {
// ...
chatwootBoot: await chatwoot.getBootData(session.shop),
};
}3. Session route — app/routes/api.chatwoot-session.ts
import type { ActionFunctionArgs } from "@remix-run/node";
import { authenticate } from "../shopify.server";
import { chatwoot } from "../chatwoot.server";
export async function action({ request }: ActionFunctionArgs) {
const { session } = await authenticate.admin(request);
return chatwoot.handleSessionRequest(request, session.shop);
}The package does not create this route for you. The widget POSTs { token } to sessionEndpoint (default /api/chatwoot-session, a path on your app's domain). If that path is proxied elsewhere in your setup (e.g. /api/* forwarded to another backend), pass a different sessionEndpoint.
4. Client
import { useChatwoot, openChat } from "@fstacksoftware/chatwoot-embed";
function App() {
const { chatwootBoot } = useLoaderData<typeof loader>();
const shop = useShop(); // your app's shop data
useChatwoot({
boot: chatwootBoot,
user: { name: shop?.name, email: shop?.email },
attributes: { app: "Kivoly", shopify_plan: shop?.planDisplayName },
disabled:
typeof window !== "undefined" &&
localStorage.getItem("supportAgent") === "true",
});
return <button onClick={openChat}>Chat with us</button>;
}Or as a component: <ChatwootWidget boot={chatwootBoot} user={...} />
setUser / setCustomAttributes are only called once user has at least one non-empty field.
How init_session is saved
- Server already has
init_session→ the token is restored in the browser and the widget reuses that conversation. - Server has no
init_session(new shop, or an admin deleted it) → the currentcw_conversationtoken of the browser (if any) is POSTed tosessionEndpointon load; otherwise it is saved as soon as Chatwoot issues the first token. - The server only saves a token that belongs to the shop's own contact.
API — everything is imported from @fstacksoftware/chatwoot-embed
Server (loader/action):
| Function | Description |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------ |
| createChatwootServer(config) | Create an instance |
| .getBootData(identifier) | { baseUrl, websiteToken, identifier, identifierHash, initSession } for the loader |
| .handleSessionRequest(request, identifier) | Handle the POST that saves init_session |
| await .identifierHash(identifier) | HMAC SHA256 (Web Crypto) |
| .getInitSession(id) / .saveInitSession(id, token) | Manual read/write |
| .clearCache(identifier?) | Drop the in-memory init_session cache |
Config options: timeoutMs (default 5000), cacheTtlMs (default 10 min, 0 = off), sessionAttribute (default init_session), logger.
React: useChatwoot({ boot, user?, attributes?, sessionEndpoint?, settings?, disabled? }), <ChatwootWidget />
Client: openChat, closeChat, toggleChat, setChatVisible, setChatAttributes, resetChatwoot, getChatwoot, loadChatwoot, onChatwootReady, identifyChatwoot
Only call
createChatwootServer(...)in a*.server.tsfile so thatapiToken/hmacTokennever end up in the client bundle.
Duplicate emails
Chatwoot does not allow two contacts with the same email, and it silently drops the email of the contact that arrives later (the request still returns 200). If several shops share one email (e.g. test stores), only the first keeps it and the others get the "Get notified by email" prompt. Disable Enable email collect box in the inbox, and send the email as a custom attribute too (e.g. shop_email) so agents can always see it.
Security
apiTokenandhmacTokenare server-only; never pass them to client code.init_sessionis only written when the token belongs to the contact of the shop that passedauthenticate.admin.- Don't log
bootdata (identifierHash,initSession) in production. - Enable Enforce user identity validation once everything works.
