Skip to main content

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 secret stays on the server

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:

ClaimRequiredRule
user_idyesYour own id for the user, up to 128 characters. Text or a number.
nameUp to 100 characters. Used in greetings and shown to your team.
emailTranscript emails go here; your team sees it. Routine emails can use it without a confirm step.
planUp to 50 characters. Routing rules can use it.
attrsUp to 10 extra values for routing rules: text (≤ 100 characters), numbers or true/false. For example { "city": "Surat", "dealer": true }.
iat, expyesIssued-at and expiry, in seconds. At most 15 minutes apart.
nonceyesA 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​

npm install @mysarthi/sdk
server.js (Express)
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 the nonce;
  • 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 like sk_live_….

It needs Node 18 or newer, works with import and require, and includes TypeScript types.

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​

SymptomCause
"expired" in Test a token, or BAD_END_USER_TOKENYour 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" errorsMissing, 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.