Skip to content

Quick start by platform

Every platform needs the same three things:

  1. A token endpoint on your backend. It checks your own session and signs a client token for that user (below).
  2. A device id generated once and stored.
  3. The client, created with the server address, the device id and a tokenProvider that calls your endpoint.

Then the app follows three observable things: the connection, the conversation list and a conversation’s messages. Do the quick start first if you need a server, keys and a conversation.

import { createUserToken } from '@agentimhq/server';
const signingKey = { kid: process.env.AGENTIM_KID, secret: process.env.AGENTIM_SECRET };
app.get('/api/chat-token', requireLogin, (req, res) => {
res.type('text/plain').send(createUserToken(signingKey, req.user.id, { expiresIn: 3600 }));
});

The client runs in the browser, so the chat is a client component.

app/chat/chat.tsx
'use client';
import { useEffect, useState } from 'react';
import { AgentIMClient } from '@agentimhq/client-web';
import { AgentIM, Chat } from '@agentimhq/react';
import '@agentimhq/react/theme.css';
export default function SupportChat({ convId }: { convId: string }) {
const [client, setClient] = useState<AgentIMClient>();
useEffect(() => {
let c: AgentIMClient | undefined;
AgentIMClient.create({
url: process.env.NEXT_PUBLIC_AGENTIM_URL!,
deviceId: (localStorage.agentimDevice ??= crypto.randomUUID()),
tokenProvider: () => fetch('/api/chat-token').then((r) => r.text()),
}).then((created) => {
c = created;
setClient(created);
created.connect();
});
return () => void c?.dispose();
}, []);
if (!client) return null;
return (
<AgentIM client={client}>
<Chat convId={convId} title="Support" />
</AgentIM>
);
}

Add your site’s origin to server.allowed_origins. All tabs of the same browser share one connection.