6 min read

Identify signed-in users

Pass a short-lived token signed by your backend so a user's conversations follow them across browsers and devices.

Every visitor gets their own conversations with your bots. By default, the widget knows a visitor only by a random id stored in their browser. If your app has its own sign-in, you can tell the widget who the user is. Their conversations then follow them to any browser or device where they sign in.

It works like this:

  1. Your backend signs a short-lived token (a JWT) for the signed-in user, using your team’s identity secret.
  2. Your page passes the token to the widget.
  3. TeamShelf checks the signature and opens that user’s conversations.

The secret never leaves your server. The browser only ever sees the signed token.

Create an identity secret

In the portal, open your team’s Setup tab, find Signed-in users, and click Create identity secret.

  • The secret starts with tss_ and is shown once. Copy it into your server’s configuration, for example as TEAMSHELF_IDENTITY_SECRET.
  • Creating a new secret replaces the old one immediately. Tokens signed with the old secret stop working, so deploy the new one right away.
  • You can also remove the secret. That turns signed-in users off: the widget then only works for anonymous visitors.

The token

The token is a JWT signed with HS256 and your identity secret. Other algorithms are rejected.

ClaimRequiredRules
subyesYour app’s user id, as a string. Up to 256 characters.
expyesExpiry, in seconds since the epoch. At most 24 hours ahead.
nbfnoNot valid before this time. Respected if present.
iatnoIssued-at time. Respected if present.
namenoThe user’s display name, up to 120 characters. The bots see it as the visitor’s name.

Other claims are ignored. TeamShelf allows 60 seconds of clock skew.

Use a stable sub that never changes for a user, such as a database id, rather than an email address. TeamShelf never sends sub to the engine that runs your bots. It uses a keyed hash of your team and sub, so the engine only sees a pseudonymous id.

An hour is a good lifetime. It’s long enough for a normal session and short enough that a leaked token is soon useless.

Sign the token on your backend

Each example signs a token for the current user that expires in one hour.

Node

With jsonwebtoken:

JavaScript
import jwt from "jsonwebtoken";

const token = jwt.sign(
  { sub: String(user.id), name: user.name },
  process.env.TEAMSHELF_IDENTITY_SECRET,
  { algorithm: "HS256", expiresIn: "1h" },
);

Python

With PyJWT:

PYTHON
import os
import time

import jwt

token = jwt.encode(
    {"sub": str(user.id), "name": user.name, "exp": int(time.time()) + 3600},
    os.environ["TEAMSHELF_IDENTITY_SECRET"],
    algorithm="HS256",
)

Ruby

With the jwt gem:

RUBY
require "jwt"

token = JWT.encode(
  { sub: user.id.to_s, name: user.name, exp: Time.now.to_i + 3600 },
  ENV.fetch("TEAMSHELF_IDENTITY_SECRET"),
  "HS256"
)

PHP

With firebase/php-jwt:

PHP
use Firebase\JWT\JWT;

$token = JWT::encode(
    ['sub' => (string) $user->id, 'name' => $user->name, 'exp' => time() + 3600],
    getenv('TEAMSHELF_IDENTITY_SECRET'),
    'HS256'
);

Pass the token to the widget

Server-rendered pages

If your server renders the page, sign the token there and put it on the script tag with data-user-token:

HTML
<script
  src="https://app.teamshelf.ai/embed.js"
  data-team="ts_yxT2lwZi7337"
  data-user-token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…"
  async
></script>

Only add the attribute for signed-in users, and don’t let a shared cache serve the page to someone else. Leave it out for everyone else; they’re anonymous visitors.

From an endpoint

In a single-page app, add a small endpoint that returns a token for the signed-in user. For example, with Express:

JavaScript
app.get("/api/teamshelf-token", requireSignIn, (req, res) => {
  const token = jwt.sign(
    { sub: String(req.user.id), name: req.user.name },
    process.env.TEAMSHELF_IDENTITY_SECRET,
    { algorithm: "HS256", expiresIn: "1h" },
  );
  res.set("Cache-Control", "no-store").json({ token });
});

Then fetch it in the browser and pass it to the widget. loadTeamShelf() is the helper from SPA mounting:

JavaScript
async function fetchTeamShelfToken() {
  const res = await fetch("/api/teamshelf-token", { credentials: "same-origin" });
  if (!res.ok) throw new Error("Not signed in");
  return (await res.json()).token;
}

const ts = await loadTeamShelf();
ts.mount({ team: "ts_yxT2lwZi7337", userToken: await fetchTeamShelfToken() });

Sign-in and sign-out

If the user signs in or out without a full page load, tell the widget:

JavaScript
// After sign-in
window.TeamShelf.identify(await fetchTeamShelfToken());

// On sign-out
window.TeamShelf.logout();
  • identify(token) remounts the widget as that user. Calling it again with a fresh token for the same user just renews the token.
  • logout() remounts the widget as a new anonymous visitor. Anonymous chats from before sign-in don’t come back, so the next person on a shared computer can’t see them.

Expired tokens

The widget sends the token to TeamShelf when it starts a session, and again when it needs a new one. If the token has expired or is rejected by then, the widget dispatches a teamshelf:token-expired event on window. Until it gets a new token, the widget shows an error for that visitor.

Listen for the event, fetch a fresh token from your backend, and pass it to identify:

JavaScript
window.addEventListener("teamshelf:token-expired", async () => {
  try {
    window.TeamShelf.identify(await fetchTeamShelfToken());
  } catch {
    // Not signed in any more: continue as an anonymous visitor.
    window.TeamShelf.logout();
  }
});

Pages that stay open for hours, like dashboards, need this handler.

Good to know

  • No merge. Conversations a visitor had anonymously, before signing in, are not merged into the signed-in user’s conversations.
  • Anonymous visitors are still welcome. Pages without a token keep working as before, with a random id per browser.
  • Retention. The visitor data setting deletes idle anonymous visitors. It doesn’t apply to signed-in users.
  • Errors. If the token is invalid, creating a session fails with 401 and the code invalid_user_token. If the team has no identity secret, it fails with 400 and identity_disabled. See Widget API.