- How the server identifies the buyer and opens a conversation
- Prepare Claude Code and a Sendbird test app
- Ask Claude Code to build the chat
- Check in the browser and with curl
- Read the security core of the generated code
- Bring this pattern to your service
- Troubleshooting
- Optional: turn on local caching
- Get started with Sendbird

Boost ops efficiency, drive revenue, & save big with omnichannel messaging
Add Seller Chat to a Next.js Marketplace with Claude Code and Sendbird CLI


- How the server identifies the buyer and opens a conversation
- Prepare Claude Code and a Sendbird test app
- Ask Claude Code to build the chat
- Check in the browser and with curl
- Read the security core of the generated code
- Bring this pattern to your service
- Troubleshooting
- Optional: turn on local caching
- Get started with Sendbird

Boost ops efficiency, drive revenue, & save big with omnichannel messaging

Boost ops efficiency, drive revenue, & save big with omnichannel messaging
This guide adds product-specific buyer–seller chat to an existing Next.js App Router marketplace. Buyers start a 1:1 conversation from a product page, and sellers receive new messages in a site-wide widget. The widget uses the Sendbird Chat SDK with a custom React UI. The server issues a Sendbird session token for the signed-in user and reuses one conversation per buyer and product.
Claude Code wrote the integration with guidance from the Sendbird Client Plugin. Sendbird CLI is a command-line tool for managing Sendbird apps and running integration checks. The CLI plugin guides sign-in and app selection. After the build, our team used the CLI to check the test app’s token policy and verify SDK connections with server-issued tokens.
You can follow this post in two ways. The sample repository has two apps. The starting app is a marketplace with a login and no chat. The finished app is the result of running the request below on the starting app, where the AI added the chat. No one edited the finished app's code by hand.
Use a Sendbird test app with no real users for both paths. The demo login trusts any of the four demo accounts.
Path A
Build it with AI
Starting app · 1-start folder
- Run the starting app and install Sendbird CLI and the plugins
- Paste the request into Claude Code
- Check the result
Path B
Run the finished app
Finished app · 2-finished folder · no plugins needed
- Node.js 20.19+, 22.13+, or 24+ (the versions the sample's ESLint toolchain supports)
- Following the sample README, copy
.env.exampleto.env.localand fill in three values: a long random string forSESSION_SECRET, the app ID from the Sendbird Dashboard forNEXT_PUBLIC_SENDBIRD_APP_ID, and an API token from the Dashboard forSENDBIRD_API_TOKEN - Run
npm ciandnpm run dev - Check the result
Both apps are on GitHub in sendbird-blog-samples/marketplace-seller-chat-nextjs.
How the server identifies the buyer and opens a conversation
The Next.js server decides who the user is from the login cookie, and the browser connects to Sendbird only with a session token the server issued. Neither the token route nor the conversation route takes the user from a user ID in the request body.
On a narrow screen, swipe the diagram sideways. The steps below describe the same flow.
- The signed-in browser sends
POST /api/chat/token. The body is empty; only the login cookie goes with it. - The server decides the user from the cookie with
getCurrentUser(). - With the API token, the server creates the Sendbird user (only if it doesn't exist) and gets a session token.
- The server returns
{ userId, token, expiresAt }, and the browser connects to Sendbird withconnect(userId, token). - To open a conversation, the browser sends only the product ID to
POST /api/chat/conversations. The buyer comes from the cookie and the seller from the product data. - The server finds or creates the channel, checks that it belongs to this product, buyer, and seller, and returns the channel URL. There is one conversation for each product and buyer.
What if the route took the user ID from the browser? Say someone signed in as the buyer Alex changes the token request body to {"userId":"seller-mina"} in the developer tools. If the route issued a token for the ID in the body, Alex could connect as the seller Mina, read all of Mina's conversations, and reply as Mina. The token route ignores the request body and still returns Alex’s token. The conversation route reads productId, identifies the buyer from the signed-in session, and looks up the seller in the product catalog.
Prepare Claude Code and a Sendbird test app
Path A If you're running the finished app, skip to Check.
You need the starting app, Sendbird CLI and the plugins, and a Sendbird test app with no real users. Sendbird CLI needs Node.js 22.x (22.23.4 or later) or 24.x (24.22.1 or later) (requirements), and the Client Plugin needs bash and jq (requirements). If you don't have a Sendbird account, create one for free and create a test app in the Sendbird Dashboard.
First, run the starting app. It stands in for a typical Next.js app with a login. Four demo accounts (two buyers, two sellers) sign in without a password, and the user is stored in a signed httpOnly cookie. Server code reads the current user with getCurrentUser() in lib/auth/session.ts.
cd 1-start # starting app folder
cp .env.example .env.local # set SESSION_SECRET to a long random string
npm install
npm run dev
http://localhost:3000 shows four products. Choose "Log in" in the header and pick Alex; the header changes to "Alex (buyer)".Next, install Sendbird CLI and the plugins.
npm install -g @sendbird/cli
sendbird --version
claude plugin marketplace add sendbird/sendbird-plugins
claude plugin install sendbird-cli@sendbird
claude plugin install sendbird-client@sendbird
These commands install the Sendbird CLI from npm, add the official Sendbird plugin marketplace, and install the Sendbird CLI plugin and the Sendbird Client Plugin.
After installing, start a new Claude Code session and run /sendbird-cli:sendbird-setup in the starting app folder to sign in to Sendbird and choose an app. For details, see the Sendbird CLI Quickstart and the plugin setup guide.
- Add the API token yourself. The starting app's
.env.examplehas onlySESSION_SECRET, so add aSENDBIRD_API_TOKEN=line to.env.localwith the token from the Sendbird Dashboard. Both the master token and secondary tokens work, but the master token can't be revoked or changed, so we recommend a secondary token. It's a secret, so don't paste it into the agent chat. - Choose a test app with no real users. The checks in this post create test users and conversations.
In a fresh project, the Client Plugin can use the app selected in Sendbird CLI if it finds no App ID in the environment or project settings. In our follow-up check, the plugin wrote the selected ID to NEXT_PUBLIC_SENDBIRD_APP_ID in .env.local. If the plugin cannot resolve an App ID during setup, follow its prompt to select or provide one. Check that the selected app and SENDBIRD_API_TOKEN belong to the same Sendbird test app (Platform API authentication). The App ID is public.
Once the app ID is set, a sendbird.json file appears in the project folder. It holds the app ID and organization ID and isn't in .gitignore. Leave it out when you push to a public repository. The sample repository for this post doesn't include it either.
Ask Claude Code to build the chat
Path A
Paste the request below into Claude Code as is, and it builds the chat feature.
This is a Next.js (App Router) marketplace app with a product list (`/`), product detail pages (`/products/[id]`), and a demo login. Products and their sellers are mock data in `lib/market/products.ts` (each product has a `sellerId`). The signed-in user comes from `getCurrentUser()` in `lib/auth/session.ts`.
Add Sendbird Chat so buyers can ask sellers about a product:
- A "Chat with seller" button on the product detail page opens a 1:1 conversation between the signed-in buyer and that product's seller, about that product. Asking about the same product again opens the same conversation. Each conversation belongs to one product and one buyer: the server must never return a conversation that belongs to another product or buyer.
- A chat widget on every page shows the signed-in user's conversations and the open conversation, with messages arriving in real time. Sellers see buyers' new questions in their widget without reloading.
- The connection stays open while the user moves between pages, and closes when the user logs out. If the user logs out while the chat is still connecting (for example, while the session token request is pending), the chat must not connect afterwards.
- If the user was offline so long that the SDK cannot fill in the missed messages (it reports a huge gap), reopen the conversation from the latest messages so nothing is silently missing, and let the user still load the older messages. The conversation list loads more conversations as the user scrolls.
- When a seller looks at their own product, do not offer to chat. Logged-out visitors see a prompt to log in instead of the chat. Logged-out visitors must not call the chat token endpoint.
Security rules:
- Users connect with session tokens that our Next.js server issues through the Sendbird Platform API, not with the user ID alone.
- Server code decides who the caller is with `getCurrentUser()`. Never trust a user ID sent from the browser, including when creating a conversation.
- The server reads the Platform API token from `SENDBIRD_API_TOKEN` in `.env.local`, which is already set. The API token must never reach the browser.
Use the Sendbird Chat SDK (`@sendbird/chat`) with our own chat UI built with Tailwind, not UIKit. Do not enable the SDK's local caching.
Name the server routes `POST /api/chat/token` (issues the session token) and `POST /api/chat/conversations` (opens the product conversation).
When the code is done, build the app, run the project's linter if it has one and fix every error, and run a check that two test users can exchange messages.
The first paragraph describes the app. Telling the agent where the product data and the current-user function are saves it time exploring the app, and it keeps the existing login.
The feature list sets the edge cases as well as what the screens do. Asking about the same product again must open the same conversation, and logging out while the chat is connecting must not leave it connected afterward. Logged-out visitors must not send token requests.
The three Security rules lines are the core of this post. Without them, the agent may choose a design that connects with the user ID alone. When you adapt the request to your app, change only the first paragraph and the feature list, and keep the Security rules as they are.
The last two paragraphs make the result easy to check. Naming the routes lets you use the check commands below as they are. We verified with local caching off; how to turn it on is in Optional: turn on local caching.
- Tools
- Claude Code + Sendbird CLI 0.6.1 +
sendbird-client1.0.7 - Steps
setupskill →sendbird-js-agent(writes the JavaScript code)- Sendbird CLI
- This run set the app ID in an environment variable ahead of time, so it skipped the CLI sign-in and app selection. The path where the plugin takes the ID of the app chosen in the CLI was checked in a separate run on 2026-11-26.
- Time
- 16 minutes of agent run time (not counting setup and installs)
- New files
- 12 — 2 routes, 7 chat UI, 2 in
lib/chat, 1 check script - Changed files
- 6 — layout, SiteHeader, product detail,
.env.example,package.json,package-lock.json - Self-check
npm run buildpassed,npm run lint0 errors, two-test-user messaging script 16/16 passed (agent report,scripts/chat-two-user-check.mjs)- Not run
- Token expiry and renewal, recovery after a long time offline (huge gap), logout while connecting — code read only
The agent also changed existing files. It put the chat widget in the root layout so the connection stays open across pages, and it replaced the header's logout form with a button that disconnects from Sendbird before logging out. It also added await connection() before the header reads the current user; the agent reported that after building, Next.js logged a prerender error for every signed-in page.
Check in the browser and with curl
Paths A and B
Use Checkpoints 2–4 to verify the build and browser behavior. Then run three curl checks to see how the server handles user identity and conversation selection. Separately from the agent's report, our team checked the same result with the items below.
npm run build succeeds, and a string search for the API token value in the build output (.next/static) finds 0 matches.
Use curl to verify that extra user and channel fields do not change the server’s choice of user or conversation. A request without a signed-in session returns 401. The first command prints the token value, so don't run it while sharing your screen.
# Sign in as Alex in the browser, then copy the market_session cookie value from the developer tools.
COOKIE='market_session=<copied value>'
# 1) Even with another user ID in the body, you get only Alex's token.
curl -s -X POST -b "$COOKIE" -H 'content-type: application/json' \
-d '{"userId":"seller-mina"}' http://localhost:3000/api/chat/token
# → {"userId":"buyer-alex", ...}
# 2) Forging the buyer, seller, and channel URL still opens the same conversation.
curl -s -X POST -b "$COOKIE" -H 'content-type: application/json' \
-d '{"productId":"leather-backpack","buyerId":"buyer-sam","sellerId":"seller-joon","channelUrl":"evil"}' \
http://localhost:3000/api/chat/conversations
# → the same channelUrl as a request without the forged fields
# 3) A request without a login returns 401.
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:3000/api/chat/token
Besides those three, we also checked the following on this post's result. Opening a conversation without signing in returns 401. The server rejects a seller opening a conversation on their own product. Our team searched the 30 files in .next/static and found no matches for either the Platform API token or the session secret. A logged-out page sends 0 token requests and logs 0 console errors.
Check with Sendbird CLI. After the run, we used Sendbird CLI to check the app's token policy and to connect to Sendbird with a token the token route issued.
tokAlex is the file holding the token the token route issued to Alex; see the CLI chat commands)$ sendbird app auth-policy get --json
# result: {"guest_user_policy":0}
$ sendbird chat sdk status --user-token-file tokAlex --as-user buyer-alex --json
# ok: true, connected: true, user_id: buyer-alex
$ sendbird chat sdk status --user-token-file tokAlex --as-user seller-mina --json
# ok: false, code: E_SDK_AUTH (sdk_code 400302)
$ sendbird app auth-policy set --guest-user-policy 2 --yes --json
# result: {"guest_user_policy":2}
$ sendbird chat sdk status --as-user marketplace-tokenless-probe --allow-guest --json
# ok: false, code: E_SDK_AUTH (sdk_code 400301)
Alex's token connected as Alex, and Sendbird refused it for Mina. Mina had signed in once before this check, so the token route had issued her a session token of her own. When we ran the same command before Mina had ever been issued a token, it connected as Mina: while the policy is "Tokenless read/write" (0), a user who has never been issued a token can connect without a valid one. That is why you block connections without a token before you deploy (see "Bring this pattern to your service" below).
We then switched the test app to "Token required" (2) ourselves. A connection without a token was refused (marketplace-tokenless-probe is a user ID that has never been issued a token). With the policy still at 2, the sample's two-user check script (scripts/chat-two-user-check.mjs), which connects Alex and Mina with tokens from the token route, passed all 16 checks, including messages in both directions.
Like the agent, we didn't run three cases: token expiry and renewal, coming back after a long time offline, and logging out while connecting.
Read the security core of the generated code
Paths A and B
Four places in the generated code decide security and connection: the session token route, the conversation channel route, the Platform API calls, and connecting and disconnecting in the browser. The finished app has 12 new files, including screen code such as the chat widget, the product chat button, and the message list; below is the code for those four places. Check the same four places when you review the code Claude Code wrote for you. Items 3 and 4 are excerpts, so copying only the code below won't build.
1. Session token route
It doesn't read the request body. getCurrentUser() decides the user from the cookie. The response has no-store so the token isn't cached.
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth/session";
import { ensureSendbirdUser, issueSessionToken } from "@/lib/chat/platform";
const NO_STORE = { "Cache-Control": "no-store" };
// Issues a Sendbird session token for the signed-in user. The user comes from the session
// cookie only; the request body is ignored. The Platform API token stays on the server.
export async function POST() {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ error: "not_signed_in" }, { status: 401, headers: NO_STORE });
}
try {
await ensureSendbirdUser(user);
const { token, expiresAt } = await issueSessionToken(user.id);
return NextResponse.json({ userId: user.id, token, expiresAt }, { headers: NO_STORE });
} catch (error) {
console.error("chat token: Platform API call failed:", error instanceof Error ? error.message : error);
return NextResponse.json({ error: "chat_unavailable" }, { status: 502, headers: NO_STORE });
}
}
2. Conversation channel route
It reads only productId from the body. The buyer comes from the cookie and the seller from the product data. It rejects a seller opening a conversation on their own product.
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth/session";
import { ConversationMismatchError, openProductConversation } from "@/lib/chat/platform";
import { getProduct } from "@/lib/market/products";
const NO_STORE = { "Cache-Control": "no-store" };
function fail(status: number, error: string) {
return NextResponse.json({ error }, { status, headers: NO_STORE });
}
// Opens the signed-in buyer's conversation about one product. The body carries only
// `productId`; the buyer comes from the session cookie and the seller from the catalog, so a
// user ID sent by the browser is never used.
export async function POST(request: Request) {
const user = await getCurrentUser();
if (!user) return fail(401, "not_signed_in");
if (!request.headers.get("content-type")?.toLowerCase().startsWith("application/json")) {
return fail(415, "json_required");
}
const body: unknown = await request.json().catch(() => null);
const productId =
body && typeof body === "object" && typeof (body as { productId?: unknown }).productId === "string"
? (body as { productId: string }).productId
: null;
if (!productId) return fail(400, "product_id_required");
const product = getProduct(productId);
if (!product) return fail(404, "product_not_found");
if (product.sellerId === user.id) return fail(400, "own_product");
try {
const channelUrl = await openProductConversation(product, user);
return NextResponse.json({ channelUrl, productId: product.id }, { headers: NO_STORE });
} catch (error) {
if (error instanceof ConversationMismatchError) return fail(409, "conversation_conflict");
console.error("chat conversation: Platform API call failed:", error instanceof Error ? error.message : error);
return fail(502, "chat_unavailable");
}
}
3. Platform API calls (server only)
The API token is read from an environment variable without the NEXT_PUBLIC_ prefix, so it stays out of the browser bundle. The channel URL is a hash of the product ID and the buyer ID, so asking about the same product again opens the same channel. Before returning a channel, the code checks that it belongs to this product, buyer, and seller. Anyone can compute this URL, so before you deploy, block channel creation from the SDK so that no other user can create a channel at the same URL first (see "Bring this pattern to your service" below). The file says it's server-only only in a comment; see "Bring this pattern to your service" for the import that enforces it.
// Sendbird Platform API calls. Server-only module: it reads SENDBIRD_API_TOKEN, which has no
// NEXT_PUBLIC_ prefix, so Next.js never puts it in the browser bundle. Import it only from
// route handlers and server components.
// …
function apiToken(): string {
const token = process.env.SENDBIRD_API_TOKEN;
if (!token) throw new Error("SENDBIRD_API_TOKEN is not set. Add it to .env.local.");
return token;
}
async function platformRequest<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> {
const response = await fetch(`${apiBase()}${path}`, {
method,
headers: {
"Content-Type": "application/json; charset=utf8",
"Api-Token": apiToken(),
},
body: body === undefined ? undefined : JSON.stringify(body),
cache: "no-store",
});
const json = (await response.json().catch(() => ({}))) as {
error?: boolean;
code?: number;
message?: string;
};
if (!response.ok || json.error) {
// The message comes from Sendbird and never contains the API token.
throw new PlatformApiError(response.status, json.code, json.message ?? `Platform API ${method} failed`);
}
return json as T;
}
// …
export async function issueSessionToken(userId: string): Promise<{ token: string; expiresAt: number }> {
const result = await platformRequest<{ token: string; expires_at: number }>(
"POST",
`/users/${encodeURIComponent(userId)}/token`,
{ expires_at: Date.now() + SESSION_TOKEN_TTL_MS },
);
return { token: result.token, expiresAt: result.expires_at };
}
// …
// One conversation per product and buyer: the URL is derived from both, so asking again
// finds the same channel and no other product or buyer can map to it.
export function productConversationUrl(productId: string, buyerId: string): string {
const digest = createHash("sha256").update(`${productId}\u0000${buyerId}`).digest("hex");
return `product_inquiry_${digest.slice(0, 48)}`;
}
// …
// The channel must say it is about this product and buyer, and have exactly the buyer and
// the product's seller as members.
function assertBelongsTo(channel: PlatformGroupChannel, expected: ProductChatData): void {
const data = parseProductChatData(channel.data);
const memberIds = new Set((channel.members ?? []).map((member) => member.user_id));
const ok =
channel.custom_type === PRODUCT_CHAT_CUSTOM_TYPE &&
data !== null &&
data.productId === expected.productId &&
data.buyerId === expected.buyerId &&
data.sellerId === expected.sellerId &&
memberIds.size === 2 &&
memberIds.has(expected.buyerId) &&
memberIds.has(expected.sellerId);
if (!ok) throw new ConversationMismatchError();
}
4. Connecting and disconnecting in the browser
The browser connects with the session token it got from the server. When the SDK requests a new session token, onSessionTokenRequired on the SessionHandler fetches one from the same route. If the user logs out while connecting, the generation number (generation) changes, so a connection that finishes late is closed right away (checked in the code, not run).
// Asks our server for a session token for the signed-in user. Resolves null when the
// session cookie is gone (logged out).
async function fetchSessionToken(signal: AbortSignal): Promise<{ userId: string; token: string } | null> {
const response = await fetch("/api/chat/token", { method: "POST", signal, cache: "no-store" });
if (response.status === 401) return null;
if (!response.ok) throw new Error(`Chat token request failed (${response.status}).`);
const body = (await response.json()) as { userId: string; token: string };
return { userId: body.userId, token: body.token };
}
// …
// Connects the signed-in user. Call it only for a signed-in user: logged-out pages never
// call the token endpoint.
export function startChat(userId: string): void {
if (state.userId === userId && (state.status === "connecting" || state.status === "connected")) return;
// Another user's connection (or a failed one) is closed first.
if (state.status !== "idle") void stopChat();
const myGeneration = ++generation;
tokenAbort?.abort();
const abort = new AbortController();
tokenAbort = abort;
setState({ ...INITIAL_STATE, status: "connecting", userId });
connecting = (async () => {
try {
const issued = await fetchSessionToken(abort.signal);
if (myGeneration !== generation) return;
if (!issued || issued.userId !== userId) throw new NotSignedInError("You are signed out.");
// A logout that is still disconnecting finishes before the next connect starts.
await disconnecting;
if (myGeneration !== generation) return;
const sb = getSendbird();
// The session handler is registered before connect.
sb.setSessionHandler(createSessionHandler(myGeneration, userId));
await sb.connect(userId, issued.token);
if (myGeneration !== generation) {
// Logged out (or switched user) while connecting: do not stay connected.
await sb.disconnect().catch(() => undefined);
return;
}
setState({ status: "connected", error: null });
} catch (error) {
if (myGeneration !== generation || isAbort(error)) return;
setState({
status: "error",
error: error instanceof NotSignedInError ? error.message : "Chat could not connect. Try reloading the page.",
});
}
})();
}
function createSessionHandler(myGeneration: number, userId: string): SessionHandler {
return new SessionHandler({
// Called only when the session token expired or was revoked.
onSessionTokenRequired: (resolve, reject) => {
if (myGeneration !== generation || !tokenAbort) {
resolve(null);
return;
}
fetchSessionToken(tokenAbort.signal)
.then((issued) => resolve(myGeneration === generation && issued?.userId === userId ? issued.token : null))
.catch((error: unknown) => (isAbort(error) ? resolve(null) : reject(error as Error)));
},
onSessionClosed: () => {
if (myGeneration !== generation) return;
void stopChat().then(() => setState({ status: "error", error: "Your chat session ended. Reload the page." }));
},
onSessionError: (error) => {
console.warn("Sendbird session refresh failed:", error.message);
},
});
}
// …
// Closes the connection: on logout, and when the widget unmounts. Safe to call at any time,
// including while the token request or connect is still pending.
export function stopChat(): Promise<void> {
generation++;
tokenAbort?.abort();
tokenAbort = null;
connecting = null;
setState(INITIAL_STATE);
const sb = sbInstance;
if (!sb) return disconnecting;
disconnecting = disconnecting.then(() => sb.disconnect().catch(() => undefined));
return disconnecting;
}
Bring this pattern to your service
To adapt this pattern to your marketplace, use your existing server-side authentication to identify the caller. Enforce your service’s rules for who can contact a seller and who can access each product conversation.
- Change the current-user function. Instead of
getCurrentUser(), use the "current user" function from your auth library (Auth.js, Clerk, Supabase Auth, and so on). Name where that function is in the request's first paragraph. - Keep the Security rules. A production app connects with session tokens the server issues, and the server creates and checks conversation channels. Sendbird CLI is a tool for development and checks.
- Add
import 'server-only';as the first line oflib/chat/platform.ts. Then Next.js fails the build if client code imports the file, which keeps the code that reads the API token out of the browser bundle (Next.js docs). - Block connections without a token before you deploy. With "Tokenless read/write" (
0), users who have never been issued a Sendbird token can connect without one. Sendbird still requires a valid token for users who have previously been issued one (user authentication). Once every client that connects to the app uses session tokens, switch the policy to "Token required" (2): runsendbird app auth-policy set --guest-user-policy 2 --yes, or use Settings > Application > Security > Access token permission in the Sendbird Dashboard (Chat SDK authentication docs). - Block channel creation from the SDK before you deploy. Conversation channel URLs are derived from the product ID and the buyer ID, so a user who can create channels from the SDK can create a channel at another buyer's URL first. The server then finds a channel that fails its checks, and that buyer gets a 409 for that product every time. For server-managed channel creation, turn off both
Allow creating open channelsandAllow creating group channelsin Sendbird Dashboard under Settings → Application → Security → Access control list (channel overview). Open channels matter too because they can take a conversation URL first, even though this sample does not use them. Your server can still create channels through the Platform API. If the setting is unavailable for your app, contact Sendbird Support. - The sample README lists known issues in the generated code and what logout ends. Its Before you deploy section covers the conversation list loading every page while the widget is closed, a slow response to an earlier "open conversation" request replacing a later one, and logout disconnecting only the current tab.
- The demo login isn't for production. The starting app's login uses demo accounts with no password.
- Invalidate the app session on your server at logout. For logout across devices, use the Platform API to revoke all Sendbird session tokens for that user. The demo only deletes its own cookie, and every token already issued stays valid until it expires.
- Set the token lifetime. This post's code issues tokens that last one hour (
SESSION_TOKEN_TTL_MSinlib/chat/platform.ts); withoutexpires_at, Sendbird's default of 7 days applies. - Results can differ from run to run. The same request can produce different file names and structure. Judge the result by the Checkpoints and the four places above, and have a person review it before you deploy.
- Not covered in this post: push notifications, file transfer, channel operator permissions, and sharing the record of created Sendbird users across multiple server instances.
Troubleshooting
/api/chat/token returns 502.
Check that .env.local has SENDBIRD_API_TOKEN and that you restarted the dev server after changing it. The dev server reads .env.local when it starts.
Logging in causes a server error that mentions "SESSION_SECRET".
The starting app signs the session cookie with SESSION_SECRET. Put a long random string in .env.local.
The build fails because cookies() or searchParams was read outside Suspense.
This app turns on cacheComponents in next.config.ts. Values that change per request (cookies, search params) must be read in a component inside <Suspense>. For a session check that compares with the current time to run at request time, call await connection() before reading.
The build fails because the Chat SDK runs on the server.
Keep Chat SDK initialization and connect inside 'use client' components so they run only in the browser.
Logged-out pages log a /api/chat/token 401 error in the console.
The chat component requests a token before knowing whether the user is signed in. Check sign-in with getCurrentUser() in a server component, and don't render the chat component when no one is signed in. The request's sentence "Logged-out visitors must not call the chat token endpoint." asks for this.
After a long time offline, messages from the middle of a conversation are missing.
After a short disconnection, MessageCollection fills in the missed messages after it reconnects. When too many messages were missed, the SDK doesn't fill them in and only calls onHugeGapDetected. Then dispose() the collection and create a new one to load from the latest messages. Load older messages with loadPrevious().
Optional: turn on local caching
This post's result has the Chat SDK's local caching off. With local caching on, the SDK stores channels and messages in the browser (IndexedDB), so it can show the stored conversations first on a return visit. Whether to turn it on depends on your service.
// One SDK instance for the whole tab, created on first use in the browser (never during
// server rendering). Local caching stays off.
let sbInstance: SendbirdGroupChat | null = null;
export function getSendbird(): SendbirdGroupChat {
if (!sbInstance) {
if (!SENDBIRD_APP_ID) throw new Error("NEXT_PUBLIC_SENDBIRD_APP_ID is not set.");
sbInstance = SendbirdChat.init({
appId: SENDBIRD_APP_ID,
modules: [new GroupChannelModule()],
localCacheEnabled: false,
}) as SendbirdGroupChat;
}
return sbInstance;
}
Before you turn it on, note that message content stays in the user's browser. If some of your users share computers, do the following.
- Call
disconnect()at logout. According to the Sendbird docs,disconnect()also clears the locally cached channels and messages.disconnectWebSocket()closes only the connection and keeps the cache, so don't use it for logout. This post's result already callsdisconnect()at logout. - To encrypt the stored data, pass
encryptanddecryptfunctions inlocalCacheEncryptionofSendbirdChat.init. Your app decides where to keep the encryption key.
If you build with Claude Code, replace the request's sentence "Do not enable the SDK's local caching." with the sentence below.
Enable the SDK's local caching. When the user logs out, call `disconnect()` so the cached channels and messages are removed from the browser.
If you ran it with that change, check Checkpoints 2–4, and after logging out, check in the browser's developer tools that no conversations are left in IndexedDB.
Get started with Sendbird
Create a test app and run the request above on your own Next.js app.
Explore Sendbird CLI and Client Plugin.
Start building with Sendbird for free. Add chat to your app with the Client Plugin's Add Chat guide.








