
Boost ops efficiency, drive revenue, & save big with omnichannel messaging
Build a WhatsApp-Style Messenger in Next.js with Claude Code and Sendbird UIKit



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

Boost ops efficiency, drive revenue, & save big with omnichannel messaging
Chatterly is a WhatsApp-style messenger built with Next.js App Router and Sendbird UIKit for React. A Next.js Route Handler reads the user ID from the app's signed session and issues a Sendbird session token for that user. The Platform API token stays on the server, and the browser passes the user's session token to SendbirdProvider as accessToken.
Claude Code built the app with guidance from the Sendbird Client Plugin. We used Sendbird CLI to check the app's token policy and test SDK connections. For a version with custom React screens and CLI checks for typing indicators and read receipts, see our earlier Chatterly build.
Instead of building the screens directly on the Chat SDK, this post uses the screens UIKit provides and restyles them to look like WhatsApp.

Use a Sendbird test app and test users for both paths below. The demo sign-in trusts the user ID you enter. Use your app's authentication for production.
Run the sample
Open the Chatterly sample README, copy .env.example to .env.local, and fill in the three environment variables. Run npm ci and npm run dev from the chatterly-nextjs folder, then open http://localhost:3000.
Recreate it with Claude Code
To build Chatterly from the original prompt, start with a new Next.js App Router project. You'll need:
- Claude Code
- Node.js 22.x (22.23.4 or later) or 24.x (24.22.1 or later), the versions the Sendbird CLI supports (requirements)
bashandjq, which the Client Plugin needs (requirements)- A Sendbird application for testing that doesn't serve real users. You can start for free.
First, we created a new Next.js app with the default settings (TypeScript, Tailwind, App Router). In our run, this installed Next.js 16.4.6 and React 19.3.0.
npx create-next-app@latest chatterly --yes
cd chatterlyThen we installed both plugins for this app folder only.
claude plugin marketplace add sendbird/sendbird-plugins --scope local
claude plugin install sendbird-cli@sendbird --scope local
claude plugin install sendbird-client@sendbird --scope localThese commands add the official Sendbird plugin marketplace and install the Sendbird CLI plugin and the Sendbird Client Plugin.
We copied an API token from Settings > Application > General > API tokens in the dashboard and put it in a new .env.local file in the project folder. We used a secondary token so that we could revoke it later.
SENDBIRD_API_TOKEN=your-api-tokenNext, start Claude Code in this folder (claude), sign in to the Sendbird CLI, and save your test application as the CLI default; Claude Code reads the App ID from that default later. /sendbird-cli:sendbird-setup walks you through installing the CLI, signing in, and choosing the application. Plugins installed with --scope local load only in Claude Code started from this folder.
Then we sent the following request.
Add a mobile-friendly WhatsApp-style messenger to this Next.js app with Sendbird UIKit for React (call it Chatterly, no WhatsApp branding): one-to-one and group chats with read receipts, typing indicators, voice messages, and reactions. Add a simple sign-in, and issue the signed-in user's Sendbird session token from a Route Handler so the API token never reaches the browser. My Sendbird API token is in .env.local as SENDBIRD_API_TOKEN. Then use the Sendbird CLI to check whether my Sendbird application still lets users connect without a token, and confirm the route gives a token only to the signed-in user.The second sentence is the one that asks for the server side: a sign-in and a Route Handler that issues the session token. Keep it when you adapt the request for your own app.
Claude Code finished without asking any questions. It wrote two more values to .env.local itself: the App ID (NEXT_PUBLIC_SENDBIRD_APP_ID) and a CHATTERLY_SESSION_SECRET that signs the demo sign-in cookie. The Client Plugin's Sendbird JS agent wrote the code with @sendbird/uikit-react 3.20.1 and @sendbird/chat 4.22.17, and didn't build the app or open it in a browser.
File | What it does |
|---|---|
| Demo sign-in. Creates the Sendbird user if it doesn't exist and sets a signed session cookie |
| Issues a Sendbird session token only to the signed-in user |
| Platform API calls. The API token is read only in this file |
| Sign-in screen, chat screen, new-chat dialog, UIKit settings |
Claude Code also replaced two parts of UIKit's chat list with its own components, the header and the empty-list screen, passed in through the renderHeader and renderPlaceHolderEmptyList props of GroupChannelList (UIKit docs).
Claude Code's output varies from run to run. When we sent the same two requests again with Client Plugin 1.0.7 instead of 1.0.5, the features and colors came out nearly the same, but file paths and names differed: for example, the token Route Handler was app/api/sendbird/session-token/route.ts and the session secret was SESSION_SECRET. That run also set no token lifetime, so Sendbird's 7-day default applied. That 1.0.7 run took about 53 and 35 minutes for the two requests; the times under "How long it took" are from the 1.0.5 run in this post.
Verify that the token route uses the signed-in session
Claude Code tested the token route with two demo users. Requests with a missing or modified session cookie returned 401. When signed in as user A, requests that named user B still returned a token for A. The agent also checked that Sendbird rejected an SDK connection as B using A's token.
After the agent run, our team changed the test app's policy to require tokens and confirmed that a connection without a token was refused. We also used Playwright to verify chat between signed-in users.
These checks show that each token belongs to the user ID in the demo session. They don't confirm who owns that user ID, since the demo sign-in accepts any ID you type.
For these checks Claude Code used two test users, A (chatterly-routecheck-a) and B (chatterly-routecheck-b).
tokA is the file holding the token the Route Handler issued to A; see the CLI chat commands)$ sendbird app auth-policy get --json
{"ok":true,"command":"sendbird app auth-policy get","effect":"read","status":"verified","target":{…},"result":{"guest_user_policy":0},"response":"data"}
$ sendbird chat sdk status --user-token-file tokA --as-user chatterly-routecheck-a --json
# ok: true, connected: true, user_id: chatterly-routecheck-a
$ sendbird chat sdk status --user-token-file tokA --as-user chatterly-routecheck-b --json
# ok: false, code: E_SDK_AUTHToken policy: The policy was guest_user_policy: 0, or "Tokenless read/write": a user who has never been issued a token can connect, read, and write without one. Claude Code offered the command that changes it to "Token required" (2), but because other clients might use the same application, it didn't change the policy and left the decision to us.
Token required: After the run, we switched the policy to "Token required" (2) ourselves and checked both sides. A connection without a token was refused, and Chatterly kept working: two users signed in and chatted, with typing indicators and read receipts.
chatterly-tokenless-probe-p2 is a user ID that has never been issued a token)$ sendbird app auth-policy set --guest-user-policy 2 --yes --json
{"ok":true,"command":"sendbird app auth-policy set","effect":"mutation","status":"accepted","target":{…},"result":{"guest_user_policy":2},"response":"data"}
$ sendbird chat sdk status --as-user chatterly-tokenless-probe-p2 --allow-guest --json
# ok: false, code: E_SDK_AUTH (sdk_code 400301)Route Handler: Claude Code started the dev server and called the Route Handler directly as A and B.
Case | Result |
|---|---|
Request without a cookie | 401 |
Forged cookie, or A's cookie altered to name B | 401 |
Signed in as A, asking for B in the query, body, or headers | 200, still A's token |
Request from another site with A's cookie | 403 |
Searching browser code and server logs for the API token | Not found |
If Claude Code left the dev server running, stop it when the checks are done. next dev can accept connections from other devices on your network, and the demo sign-in issues a token for any user ID.
Refine the messenger UI
We changed the design with a second, separate request, and its last sentence told Claude Code to leave the behavior as it was.
Restyle Chatterly so it looks and feels like WhatsApp, in both light and dark mode: a green header, a plain chat background that is beige in light mode, light green outgoing bubbles, and check marks that turn blue when a message is read. Keep the name Chatterly, use your own shades instead of WhatsApp's exact colors, and don't use WhatsApp's logo. Only change the look; keep the chat behavior as it is and don't use the Sendbird CLI.Claude Code changed the primary green and the blue of the read check marks through UIKit's color variables (colorSet), and overrode the rest with CSS rules in components/chatterly/chatterly-uikit.css. All the colors are defined in app/globals.css, in a light set and a dark set. The design request didn't swap out any components.

Check a chat between two users
We did this step ourselves. We started the built app with npm start and used Playwright to sign in as Alice and Bob (and Carol for a group) and check one-to-one and group chats, typing indicators, read receipts, voice messages, and reactions on both screens. Everything worked as expected. The only console error was the 401 the token Route Handler returns when the page loads before sign-in, which is expected.
To try it yourself, run npm run dev and open http://localhost:3000. Sign in as the second user from another browser or a private window, because windows of one browser profile share the session cookie.
- Reactions show up only when they're also enabled in the application settings.
- Voice messages need microphone permission, and browsers allow the microphone only on
localhostor HTTPS.

Bob is typing... in the list
How long it took
Each time is measured from when we sent the request to Claude Code's last output for that request.
Request | Time |
|---|---|
Initial build and CLI check | 49 min 39 sec |
Design refinement | 32 min 21 sec |
The build request took longer because it also covered sign-in, the token Route Handler, and the CLI checks.
Connect it to your service
The biggest change when you move this to a real service is sign-in. Everything else is listed under "Before you launch" at the end of this section.
How the token flows
- On sign-in, the sign-in Route Handler creates the Sendbird user if needed and sets a signed session cookie.
- The browser calls
POST /api/sendbird/token, and the Route Handler issues a session token for the user in the cookie through the Platform API. - The browser passes the token to
SendbirdProviderasaccessToken. When the SDK requests a new session token, theonSessionTokenRequiredcallback inconfigureSessionfetches one from the same Route Handler. To test renewal, we cut the token lifetime to one minute in a local copy and signed in two users. Each page fetched a new token from the Route Handler shortly before its token expired, and messages kept going both ways after two renewals.
See the Platform API docs for the session token API and its default lifetime, the Chat SDK authentication docs for the session handler, and the Add Chat guide for connecting users with server-issued tokens.
app/api/sendbird/token/route.ts, exactly as Claude Code wrote it. It only issues tokens and never touches channel membership.import type { NextRequest } from 'next/server';
import { serverErrorResponse } from '@/lib/server/errors';
import { isCrossSiteRequest, jsonNoStore } from '@/lib/server/http';
import { issueSessionToken } from '@/lib/server/sendbird-platform';
import { SESSION_COOKIE_NAME, clearSessionCookie, readSessionCookieValue, setSessionCookie } from '@/lib/server/session';
// POST /api/sendbird/token
// Request: the chatterly_session cookie. Nothing else is read: no query string, no body, no header names a user.
// Response: 200 {"userId", "nickname", "token", "expiresAt"} — a Sendbird session token for the signed-in user only
// (expiresAt: Unix ms), and the session cookie renewed for another 7 days
// 401 {"error": "not_signed_in"} (no cookie) | {"error": "invalid_session"} (altered or expired cookie; cleared)
// 403 cross_site_request, 500 server_not_configured | internal_error, 502 sendbird_request_failed
// Every response has Cache-Control: no-store. GET and other methods get 405 from Next.js.
//
// The browser calls this before it connects and again whenever the Sendbird SDK asks for a new token
// (SessionHandler.onSessionTokenRequired in components/chatterly/SignedInChat.tsx).
// source: https://sendbird.com/docs/chat/sdk/v4/javascript/application/authenticating-a-user/authentication ("Set a session handler")
// source: https://sendbird.com/docs/chat/platform-api/v3/user/managing-session-tokens/issue-a-session-token
export async function POST(request: NextRequest) {
if (isCrossSiteRequest(request)) return jsonNoStore({ error: 'cross_site_request' }, 403);
try {
const result = readSessionCookieValue(request.cookies.get(SESSION_COOKIE_NAME)?.value);
if (!result.ok) {
const response = jsonNoStore({ error: result.reason === 'missing' ? 'not_signed_in' : 'invalid_session' }, 401);
if (result.reason === 'invalid') clearSessionCookie(response);
return response;
}
// The only user this route ever issues a token for: the one in the signed session cookie.
const { userId, nickname } = result.session;
const { token, expiresAt } = await issueSessionToken(userId);
const response = jsonNoStore({ userId, nickname: nickname ?? null, token, expiresAt });
setSessionCookie(response, result.session);
return response;
} catch (error) {
return serverErrorResponse(error, 'POST /api/sendbird/token');
}
}The Route Handler relies on four helper files:
lib/server/session.ts: checks the session cookie's signature and expiry and reads the user ID from it.lib/server/http.ts: rejects cross-site requests and builds JSON responses withCache-Control: no-store.lib/server/sendbird-platform.ts: reads the API token and calls the Sendbird Platform API (excerpt below).lib/server/errors.ts: logs server errors and answers the browser without details.
lib/server/sendbird-platform.ts. The file imports server-only on its first line, so Next.js fails the build if client code imports this file. That keeps the code that reads the API token out of the browser bundle.import 'server-only';
import { SENDBIRD_APP_ID } from '@/lib/sendbird/config';
import { SendbirdPlatformError, ServerConfigError } from './errors';
// …
/** Lifetime of each Sendbird session token Chatterly issues. The browser asks for a new one when it expires. */
export const SESSION_TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
function platformSettings(): { baseUrl: string; apiToken: string } {
const apiToken = (process.env.SENDBIRD_API_TOKEN ?? '').trim();
const missing: string[] = [];
if (!SENDBIRD_APP_ID) missing.push('NEXT_PUBLIC_SENDBIRD_APP_ID');
if (!apiToken) missing.push('SENDBIRD_API_TOKEN');
if (missing.length > 0) throw new ServerConfigError(missing);
return { baseUrl: `https://api-${SENDBIRD_APP_ID}.sendbird.com/v3`, apiToken };
}
// …
/** Issues a Sendbird session token for `userId`. Call it only with the user ID of the signed-in session. */
export async function issueSessionToken(userId: string): Promise<{ token: string; expiresAt: number | null }> {
const response = await platformRequest(`/users/${encodeURIComponent(userId)}/token`, 'POST', {
expires_at: Date.now() + SESSION_TOKEN_TTL_MS,
});
// …
}components/chatterly/SignedInChat.tsx'use client';
// …
import { SendbirdErrorCode, SessionHandler } from '@sendbird/chat';
import { SendbirdProvider, type SendbirdProviderProps } from '@sendbird/uikit-react/SendbirdProvider';
// …
import '@sendbird/uikit-react/dist/index.css';
// …
export function SignedInChat({ userId, nickname, accessToken }: SignedInChatProps) {
// …
const configureSession: SendbirdProviderProps['configureSession'] = () => {
const handler = new SessionHandler();
handler.onSessionTokenRequired = (resolve, reject) => {
// resolve(null) gives up the session: this browser is signed out or signed in as someone else.
fetchSessionTokenFor(userId).then(resolve, reject);
};
// …
return handler;
};
// …
// The provider connects again only when appId or userId changes; a new accessToken value alone
// does not reconnect, so token renewal goes through configureSession.
return (
<SendbirdProvider
appId={SENDBIRD_APP_ID}
userId={userId}
accessToken={accessToken}
configureSession={configureSession}
// …
>
{/* … */}
</SendbirdProvider>
);
}SendbirdApp (@sendbird/uikit-react/App), the all-in-one component, has no configureSession prop as of 3.20.1, so it can't renew an expired token. Session tokens always expire, so to renew them without a page reload, compose GroupChannelList and GroupChannel inside SendbirdProvider yourself, as Chatterly does.
Before you launch
- Replace the demo sign-in with real authentication such as Auth.js, Clerk, or Supabase Auth; the demo sign-in trusts whatever user ID is entered.
- Invalidate the app session on your server at sign-out. For sign-out across devices, use the Platform API to revoke all Sendbird session tokens for that user. The demo only clears its own cookie. A cookie copied before sign-out keeps getting tokens, and every token already issued stays valid for up to 24 hours; the demo issues a new one on each page load. sendbird/sendbird-uikit-nextjs-sample, a human-reviewed sample with the same structure (sign-in, token Route Handler, UIKit), revokes the tokens at sign-out.
- Keep
SENDBIRD_API_TOKENon the server only, without theNEXT_PUBLIC_prefix, and set every variable the code reads on your hosting service. Our code also readsNEXT_PUBLIC_SENDBIRD_APP_ID(set it before you build) and aCHATTERLY_SESSION_SECRETof at least 32 characters. - Set the token lifetime. Our code uses 24 hours (
SESSION_TOKEN_TTL_MS); withoutexpires_at, Sendbird's default of 7 days applies. - Block connections without a token. The App ID is public, so while the policy is "Tokenless read/write" (
0), anyone can connect without going through this Route Handler. Once all your clients use 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 dashboard (Chat SDK authentication docs).
Fix errors you may hit with UIKit in Next.js
UIKit renders only in the browser. So app/page.tsx, a Server Component, renders only <ChatterlyLoader />, and ChatterlyLoader, a "use client" file, loads the chat code with next/dynamic and ssr: false. This avoids the first three errors below; the last two come from microphone permission and a Next.js setting.
components/chatterly/ChatterlyLoader.tsx — exactly as Claude Code wrote it.'use client';
import dynamic from 'next/dynamic';
import { SplashScreen } from './SplashScreen';
// Sendbird UIKit runs only in the browser, so Chatterly's chat code is loaded on the client only:
// the server renders the splash screen, and the Sendbird SDK is never imported or initialized during
// server rendering. `ssr: false` is allowed only in a Client Component like this one.
// source: node_modules/next/dist/docs/01-app/02-guides/lazy-loading.md ("Skipping SSR")
// source: knowledge/curated/js/cross-cutting/troubleshooting.md ("Next.js: … during server rendering")
const ChatterlyApp = dynamic(() => import('./ChatterlyApp'), {
ssr: false,
loading: () => <SplashScreen />,
});
export function ChatterlyLoader() {
return <ChatterlyApp />;
}Error message | Cause and fix |
|---|---|
| Move the |
| UIKit was imported in a Server Component. Import it from a |
| UIKit was rendered on the server. Load it with |
| Allow the microphone in the browser and system settings. |
| A Server Component called |
Build your own WhatsApp-style messenger
The Chatterly code from this post is in the chatterly-nextjs folder of sendbird/sendbird-blog-samples. The app code is exactly as Claude Code left it; we only wrote the README and .env.example. For a general chat app built on the same structure, start from the human-reviewed sendbird-uikit-nextjs-sample mentioned above.
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.
Chatterly is a demonstration app inspired by a mobile-messaging pattern. It is not affiliated with WhatsApp and does not use WhatsApp's logo.








