# Log visitors in

> Know who your logged-in visitors are, keep their chats on every device, and let the AI agent act on their account safely.

When someone is logged in to your site, the widget can know who they are. Your server signs a short-lived token for them, and the widget sends it with every chat request. Then:

- What they write while logged in follows them to every device and browser where they log in.
- Nobody else can open those conversations, even on the same computer.
- The AI agent gets their name, email and any other facts you sign, as facts you vouch for, not text anyone could type.
- Your own tools learn who they are: help.ai sends each call a signed **Txn-Token** your server can check.
- In **Inbox**, their conversations show a **Logged in** tag with their name and your id for them.

Visitors who aren't logged in keep chatting anonymously, as before. help.ai never logs anyone in: your site does, with whatever login you use today.

## What you need

- The deployment's **Secret key**, under **Parameters** on its **Install** tab. Select the eye icon to reveal it. Keep it on your server, in `HELP_AI_SECRET_KEY`: anyone who has it can log in as any of your users.
- Your login page's address, for the **Log in** button.
- Widget 1.16.0 or later. The **Install** tab's snippets load a version that has it.

The **Install** tab's **Login** section has these steps with the same snippets, ready to copy.

## 1. Sign a token on your server

The token is a JWT signed with HS256 and the deployment's secret key, with the header `typ: JWT`. No other algorithm is accepted.

| Claim | What it is |
| --- | --- |
| `sub` | Required. Your own id for the user, as text, up to 255 characters. Use your database id, not your login provider's id, so changing provider later keeps the same person |
| `iat` | Required. When you signed it, in seconds since 1970 |
| `exp` | Required. When it expires, in seconds since 1970: at most 24 hours after `iat`. The widget asks for a new one when it runs out |
| `name` | Optional. Their name, up to 200 characters |
| `email` | Optional. Only an email your site has confirmed: help.ai and your tools treat it as proof |
| `phone_number` | Optional. Their phone number |
| Anything else | Optional facts, such as `tier` or `plan`. The AI agent and your team see them |

Leave out a claim you don't have. One bad claim (an empty `name`, an `email` that isn't an address) makes the whole token invalid. Tokens longer than 4,096 characters are refused. help.ai allows 60 seconds of difference between your server's clock and its own.

### JavaScript (Node, Bun, Deno, edge)

The widget's package signs it for you:

```js
import { signUserToken } from '@helpai/elements/server';

export function signHelpAiToken(user) {
  // Valid for 12 hours by default (at most 24). Leave out what you don't have: an empty name makes the token invalid.
  return signUserToken({ secretKey: process.env.HELP_AI_SECRET_KEY, user: { sub: String(user.id), ...(user.name && { name: user.name }), plan: user.plan } });
}
```

### Python

```python
import os, time
import jwt  # PyJWT

def sign_help_ai_token(user):
    now = int(time.time())
    claims = {"sub": str(user.id), "iat": now, "exp": now + 12 * 3600}
    if user.name:
        claims["name"] = user.name
    return jwt.encode(claims, os.environ["HELP_AI_SECRET_KEY"], algorithm="HS256", headers={"typ": "JWT"})
```

### PHP

```php
<?php
use Firebase\JWT\JWT; // firebase/php-jwt

function signHelpAiToken($user): string
{
    $now = time();
    $claims = ['sub' => (string) $user->id, 'iat' => $now, 'exp' => $now + 12 * 3600];
    if (!empty($user->name)) {
        $claims['name'] = $user->name;
    }
    return JWT::encode($claims, getenv('HELP_AI_SECRET_KEY'), 'HS256', null, ['typ' => 'JWT']);
}
```

## 2. Give the widget the token

Sign the token while your server renders the page for a logged-in user, and pass it to the widget. To let the widget refresh it, give it a function that returns a fresh token instead, for example from an endpoint on your server that only a logged-in user reaches.

```js
window.HelpAI = window.HelpAI || function () { (HelpAI.q = HelpAI.q || []).push(arguments); };

HelpAI('login', () => fetch('/account/help-ai-token').then((res) => res.text()));
```

- **`<web-ai-chat>` element:** `document.querySelector('web-ai-chat').login(getToken)`
- **NPM package:** pass `userToken: getToken` to `init()`, or call `chat.login(getToken)` after they log in.
- **React:** `<HelpAI publicKey="…" aiAgentDeploymentId="…" userToken={getToken} />`

Logging in during a conversation needs no reload: the next message carries the token, and the conversation becomes theirs.

## 3. Add the Log in button

On the deployment's **Settings** tab, set **Login URL** to your login page with `{returnTo}` where it reads the page to come back to:

```text
https://example.com/login?return_to={returnTo}
```

Visitors who aren't logged in then see "Log in for faster, more personalized support" above the message box, with **Log in** and an X that hides it until they close the browser. **Log in** saves what they were typing and takes them to your login page; after they log in and come back, the chat reopens where they left it.

If your site logs people in with its own pop-up, listen for the widget's `loginRequested` event instead: the widget then doesn't leave the page, and you call `chat.login(token)` once they're in.

```js
chat.on('loginRequested', ({ returnTo }) => openYourLoginModal({ returnTo }));
```

Turn on **Only logged-in visitors can chat** to replace the message box with a Log in screen for anyone who isn't logged in.

## 4. Log in on your support portal

A help.ai portal, and any other site help.ai hosts for you, uses the same login. When the deployment has a **Login URL**, the portal header shows **Log in**. It sends the visitor to your **Login URL** with `{returnTo}` set to the portal's login address, such as `https://support.example.com/login/callback`. Point the **Login URL** at one route on your server that sends them back with a fresh token:

```text
https://example.com/help-ai-login?return_to={returnTo}
```

```js
import { loginReturnPage, signUserToken } from '@helpai/elements/server';

// GET /help-ai-login?return_to=…
export async function helpAiLogin(request, user) {
  const url = new URL(request.url);
  // Not logged in: your own login page, which comes back here once they are.
  if (!user) return Response.redirect(new URL(`/login?return_to=${encodeURIComponent(url.pathname + url.search)}`, url), 302);
  const userToken = await signUserToken({ secretKey: process.env.HELP_AI_SECRET_KEY, user: { sub: String(user.id), name: user.name } });
  return loginReturnPage({ returnTo: url.searchParams.get('return_to'), siteOrigins: process.env.HELP_AI_SITE_ORIGINS, userToken }) ?? Response.redirect(new URL('/', url), 302);
}
```

Set `HELP_AI_SITE_ORIGINS` to your portal's address, such as `https://support.example.com` (several separated by commas). `loginReturnPage` sends the token only to `/login/callback` on one of those addresses, in a form posted at once, so it never shows in the address bar, the browser's history or a log. For any other `return_to` it returns nothing and your route opens your home page. Without JavaScript on your server, do the same yourself. Send a token only when `return_to` parses to an origin that is exactly one of your portal addresses and its path is exactly `/login/callback`, with no query; for anything else, redirect to your home page without a token. Then answer with a page whose form posts the token in a field named `user_token` to `return_to` at once (HTML-escape both), sent with `Cache-Control: no-store` and `Referrer-Policy: strict-origin`.

The portal accepts the token only from your login page's site and only for a login started in that browser, logs the chat in, signs them in to the portal as a member, and opens the page they were on. If the token is expired or wrong, the portal says "Couldn't log you in" with **Log in again**.

## 5. Log them out

When your user logs out, start the widget over so the next person on that computer sees nothing of theirs:

```js
HelpAI('reset');
```

On `<web-ai-chat>` or an NPM install it's `chat.reset()`; in React, drop the `userToken` prop. To switch to another account, call `reset()` first, then `login` with the new user's token.

## What your team, the agent and your tools see

- In **Inbox**, a logged-in visitor's conversation shows **Logged in** with their name and your id for them, and the facts you signed. Emails show **Sender confirmed** when the sender's domain signed the email (DMARC passed), else **Sender not confirmed**.
- The AI agent gets the facts you signed in their own section, never as instructions.
- Your MCP server or API gets a **Txn-Token** header on each call for a logged-in visitor or a confirmed email sender. See [Check who a tool call is for](#check-who-a-tool-call-is-for).

## Check who a tool call is for

Add a **Txn-Token secret** to the integration (**Integrations** → your server → **Txn-Token secret** → **Generate**). help.ai then signs a token for every call it makes to your server on behalf of a logged-in visitor or a confirmed email sender:

| Claim | What it is |
| --- | --- |
| `typ` (header) | `txntoken+jwt` |
| `aud` | Your server's address, such as `https://api.example.com` |
| `sub` | Your id for the logged-in user. Absent for an email sender |
| `txn` | The help.ai conversation |
| `exp` | Five minutes after it was signed |
| `tctx.verified_by` | `user_token` (logged in) or `email_signature` (an email whose domain signed it) |
| `tctx.email`, `tctx.name` | What help.ai knows about them |

Check the HS256 signature with the secret, `typ`, that `aud` is your own address and that it hasn't expired; in JavaScript, `verifyTxnToken({ token, secretKey, audience })` from `@helpai/elements/server` does all of it. Then act only for `sub`, or, when `verified_by` is `email_signature`, only on records with that email, never as an account. Ignore the person or email the AI passes in the call's arguments when they differ. Without a valid token, treat the call as anonymous.

## Good to know

- Each record keeps who wrote it. Chats from before they logged in stay with that browser; a chat they continue while logged in becomes theirs and follows them.
- The same id across your website chat, contact form and portal is one person, with one memory of them.
- Logging in with Auth0, Okta, Cognito, Clerk, Firebase or Google changes nothing here: once they're logged in to your site, sign the token from your session. Your provider's own id token isn't accepted.
- Logging out at your login provider doesn't log the chat out before the token's `exp`: call `reset()` when they log out of your site.
- **Forget me** in the widget erases a logged-in visitor's conversations on every device. For a privacy request, an owner or admin can erase everything kept for a visitor from their conversation in **Inbox**.

## Troubleshooting

- **Requests fail with 401 `USER_TOKEN_INVALID`:** the token is malformed, signed with another key or algorithm, expired, or has a bad claim. Each deployment has its own secret key. The widget asks your function for a fresh token and tries once more; with a fixed token it carries on as an anonymous visitor with the Log in bar.
- **New tokens fail straight away:** check that the token has `iat` and an `exp` at most 24 hours later, and your server's clock: one more than a minute ahead makes the token look like it comes from the future.
- **Chats don't follow the user to another device:** `sub` must be the same id for the same user everywhere, such as your database id.
- **An old chat says it can't be found:** it belongs to someone who was logged in. The widget starts a new conversation and sends the message there.
- **`HelpAI is not defined`:** your `login` call runs before the widget's script. Add the first line from step 2.
