Signing the token on your server
Add one route to your server that is only reachable by a logged-in user and returns a fresh token. The widget calls it when it needs one.
The SDK secret (sk_live_…) signs tokens on your behalf. Anyone who has it can impersonate any of your customers in the chat. Keep it in an environment variable on your server. Never put it in a web page, a mobile app, or a repository.
The token
A JWT, algorithm HS256, signed with the SDK secret from Widget & SDK:
| Claim | Required | Rule |
|---|---|---|
user_id | yes | Your own id for the user, up to 128 characters. Text or a number. |
name | Up to 100 characters. Used in greetings and shown to your team. | |
email | Transcript emails go here; your team sees it. Routine emails can use it without a confirm step. | |
plan | Up to 50 characters. Routing rules can use it. | |
attrs | Up to 10 extra values for routing rules: text (≤ 100 characters), numbers or true/false. For example { "city": "Surat", "dealer": true }. | |
iat, exp | yes | Issued-at and expiry, in seconds. At most 15 minutes apart. |
nonce | yes | A random id of 16–64 letters, digits, - or _. Each token works once. |
Optional values that are empty (null, "" or only spaces) are simply ignored, so you can pass your user's fields as they are: a user with no email still gets a signed-in chat.
Sign a new token for every request to your route. Don't cache tokens.
Examples
- Node.js (SDK)
- Next.js
- Node.js (any JWT library)
- Python
- PHP
npm install @mysarthi/sdk
import { sign } from '@mysarthi/sdk';
app.get('/sarthi-token', requireLogin, (req, res) => {
res.json({
token: sign(
{
user_id: req.user.id,
name: req.user.name,
email: req.user.email,
plan: req.user.plan,
attrs: { city: req.user.city },
},
process.env.SARTHI_SDK_SECRET,
),
});
});
What sign() does for you:
- fills in
iat,exp(15 minutes; pass{ expiresInSeconds }for 60–900) and thenonce; - leaves out empty values and cuts longer text to the limits above;
- throws a clear error for a missing
user_id, a wrong type or a secret that doesn't look likesk_live_….
It needs Node 18 or newer, works with import and require, and includes TypeScript types.
import { sign } from '@mysarthi/sdk';
import { NextResponse } from 'next/server';
import { currentUser } from '@/lib/auth'; // your own session helper
export async function GET() {
const user = await currentUser();
if (!user) return NextResponse.json({ error: 'not signed in' }, { status: 401 });
const token = sign(
{ user_id: user.id, name: user.name, email: user.email, plan: user.plan },
process.env.SARTHI_SDK_SECRET,
);
return NextResponse.json({ token }, { headers: { 'cache-control': 'no-store' } });
}
The page then uses getEndUserToken: () => fetch('/api/sarthi-token').then((r) => r.json()).then((d) => d.token) (see React and Next.js).
import { randomBytes } from 'node:crypto';
import jwt from 'jsonwebtoken';
const saarthiToken = (user) =>
jwt.sign(
{
user_id: String(user.id),
name: user.name,
email: user.email,
plan: user.plan,
nonce: randomBytes(24).toString('base64url'),
},
process.env.SARTHI_SDK_SECRET,
{ algorithm: 'HS256', expiresIn: '15m' }, // adds iat and exp
);
pip install PyJWT
import os, secrets, time
import jwt
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
@login_required
def saarthi_token(request):
now = int(time.time())
user = request.user
payload = {
"user_id": str(user.id),
"name": user.get_full_name() or user.username,
"email": user.email,
"iat": now,
"exp": now + 900, # 15 minutes, the maximum
"nonce": secrets.token_urlsafe(24), # 32 characters
}
token = jwt.encode(payload, os.environ["SARTHI_SDK_SECRET"], algorithm="HS256")
return JsonResponse({"token": token})
composer require firebase/php-jwt
use Firebase\JWT\JWT;
Route::middleware('auth')->get('/sarthi-token', function () {
$user = auth()->user();
$now = time();
$token = JWT::encode([
'user_id' => (string) $user->id,
'name' => $user->name,
'email' => $user->email,
'iat' => $now,
'exp' => $now + 900, // 15 minutes, the maximum
'nonce' => rtrim(strtr(base64_encode(random_bytes(24)), '+/', '-_'), '='),
], env('SARTHI_SDK_SECRET'), 'HS256');
return response()->json(['token' => $token])->header('Cache-Control', 'no-store');
});
Plain PHP without a library is in the WordPress guide.
Rotating the secret
Widget & SDK → Rotate. The new secret is shown once. The old one keeps working for 24 hours, so you can update your server without a gap. If the secret leaked, choose "stop the old one now" instead.
Common mistakes
| Symptom | Cause |
|---|---|
"expired" in Test a token, or BAD_END_USER_TOKEN | Your server's clock is off, or exp is more than 15 minutes after iat. Sync the clock with NTP. |
| "bad signature" | A different secret (an old one after rotation, or a copy-paste with a trailing space), or the token was signed with RS256 instead of HS256. |
| "nonce" errors | Missing, shorter than 16 or longer than 64 characters, or the same nonce twice (a cached token). |
| The visitor sees "Please refresh the page to start a new chat." | The page passed a single endUserToken that was already used. Use getEndUserToken so the widget can ask for a fresh one. |