Connect your users (no second login)
Your app already knows who the user is. With a client JWT, your backend vouches for that user and the Ethora chat component opens already signed in, with no Ethora login screen. It takes one backend route and one helper file.
How the flow works
- Your frontend calls your own backend, for example
GET /api/ethora/token, with the session it already uses. - The backend makes sure the user exists in your Ethora app (
POST /v1/users/batchwith a server JWT), signs a client JWT with the app secret and returns{ "token": "<jwt>" }. - The frontend passes the token to the chat component (
jwtLogin). - The chat exchanges it at
POST /v1/users/client(headerx-custom-token) for{ user, token, refreshToken }and connects.
The app secret signs every token, so this mode always needs a server. The secret must never reach a browser or mobile bundle, so never give it a public env prefix (VITE_*, NEXT_PUBLIC_*, EXPO_PUBLIC_*).
Find your app ID and app secret
- App secret: admin panel (
https://app.chat.ethora.comon Ethora Cloud) → your app → Settings → API → Secret. - App ID: the app's
_id. It is the last segment of the app's admin URL,https://app.chat.ethora.com/app/admin/apps/<appId>. GET /v1/apps(called with an admin user token) returns both, as_idandappSecret.
Keep them in server-side environment variables: ETHORA_APP_ID, ETHORA_APP_SECRET and, optionally, ETHORA_API_URL (default https://api.chat.ethora.com).
Server JWT vs client JWT
Both are HS256 JWTs signed with the app secret. They differ in data.type and in who uses them.
| Server JWT | Client JWT | |
|---|---|---|
data claim | { "type": "server", "appId": "<APP_ID>" } | { "type": "client", "appId": "<APP_ID>", "userId": "<your user id>" } |
| Used by | Your backend | The chat component |
| Sent to | User and room management endpoints, header x-custom-token | POST /v1/users/client, header x-custom-token |
| Lifetime in the examples | 1 hour | 12 hours |
userId is your own stable id for the user (database id, UUID). The Ethora username becomes <appId>_<userId>, and the same userId always maps to the same chat account on web and mobile.
Create the user before the first login
POST /v1/users/client never creates users. For an unknown userId it answers 401 with code: "USER_NOT_FOUND". Create the user first with POST /v1/users/batch and a server JWT:
{ "bypassEmailConfirmation": true, "usersList": [{ "uuid": "<userId>", "email": "ann@example.com", "firstName": "Ann", "lastName": "Lee" }] }uuidmust equal theuserIdyou put in the client JWT.firstNameandlastNameare required and must be at least 2 characters, otherwise the API answers422 VALIDATION_ERROR. If you only have one name field, split it and fall back to a placeholder such asUser.- Call it at sign-up in your system, or lazily before the first token (as below). An "already exists" error is fine.
Node.js example (no dependencies)
Node.js 18 or later (global fetch, node:crypto).
// ethora-token.js — Node.js >= 18, no dependencies
const { createHmac } = require('node:crypto');
const APP_ID = process.env.ETHORA_APP_ID;
const APP_SECRET = process.env.ETHORA_APP_SECRET;
const API_URL = (process.env.ETHORA_API_URL || 'https://api.chat.ethora.com').replace(/\/v[12]\/?$/, '');
const b64url = (b) => Buffer.from(b).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
function sign(payload) {
if (!APP_ID || !APP_SECRET) throw new Error('ETHORA_APP_ID / ETHORA_APP_SECRET are not set');
const h = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
const b = b64url(JSON.stringify(payload));
return `${h}.${b}.${b64url(createHmac('sha256', APP_SECRET).update(`${h}.${b}`).digest())}`;
}
const now = () => Math.floor(Date.now() / 1000);
function clientToken(userId, { ttlSeconds = 12 * 3600 } = {}) {
return sign({ data: { type: 'client', appId: APP_ID, userId: String(userId) }, iat: now(), exp: now() + ttlSeconds });
}
function serverToken({ ttlSeconds = 3600 } = {}) {
return sign({ data: { type: 'server', appId: APP_ID }, iat: now(), exp: now() + ttlSeconds });
}
const ensured = new Set(); // per-process cache; store a flag in your database in production
async function ensureEthoraUser({ userId, email, firstName, lastName }) {
const key = String(userId);
if (ensured.has(key)) return;
const res = await fetch(`${API_URL}/v1/users/batch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-custom-token': serverToken() },
body: JSON.stringify({ bypassEmailConfirmation: true, usersList: [{ uuid: key, email, firstName, lastName }] }),
});
if (!res.ok) {
const text = await res.text();
if (!/exist|already|duplicate/i.test(text)) throw new Error(`Ethora user sync failed: ${res.status} ${text.slice(0, 300)}`);
}
ensured.add(key);
}
module.exports = { clientToken, serverToken, ensureEthoraUser };// routes/ethora.js — Express; mount after your auth middleware so req.user is set
const express = require('express');
const { clientToken, ensureEthoraUser } = require('../ethora-token');
const router = express.Router();
router.get('/api/ethora/token', async (req, res) => {
if (!req.user) return res.status(401).json({ error: 'unauthenticated' });
try {
const { id, email, firstName, lastName } = req.user;
await ensureEthoraUser({ userId: id, email, firstName, lastName });
res.json({ token: clientToken(id) });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
module.exports = router;Python example (PyJWT)
Produces the same tokens and the same /v1/users/batch request as the Node.js helper.
# ethora_token.py — Python 3.8+, PyJWT 2.x (pip install PyJWT); HTTP via the standard library
import json, os, re, time, urllib.error, urllib.request
import jwt
APP_ID = os.environ.get("ETHORA_APP_ID")
APP_SECRET = os.environ.get("ETHORA_APP_SECRET")
API_URL = re.sub(r"/v[12]/?$", "", os.environ.get("ETHORA_API_URL") or "https://api.chat.ethora.com")
def _sign(payload):
if not APP_ID or not APP_SECRET:
raise RuntimeError("ETHORA_APP_ID / ETHORA_APP_SECRET are not set")
return jwt.encode(payload, APP_SECRET, algorithm="HS256")
def client_token(user_id, ttl_seconds=12 * 3600):
now = int(time.time())
return _sign({"data": {"type": "client", "appId": APP_ID, "userId": str(user_id)}, "iat": now, "exp": now + ttl_seconds})
def server_token(ttl_seconds=3600):
now = int(time.time())
return _sign({"data": {"type": "server", "appId": APP_ID}, "iat": now, "exp": now + ttl_seconds})
_ensured = set() # per-process cache; store a flag in your database in production
def ensure_ethora_user(user_id, email, first_name, last_name):
key = str(user_id)
if key in _ensured:
return
body = {"bypassEmailConfirmation": True,
"usersList": [{"uuid": key, "email": email, "firstName": first_name, "lastName": last_name}]}
req = urllib.request.Request(f"{API_URL}/v1/users/batch", data=json.dumps(body).encode(), method="POST",
headers={"Content-Type": "application/json", "x-custom-token": server_token()})
try:
urllib.request.urlopen(req, timeout=30).close()
except urllib.error.HTTPError as e:
text = e.read().decode("utf-8", "replace")
if not re.search(r"exist|already|duplicate", text, re.I):
raise RuntimeError(f"Ethora user sync failed: {e.code} {text[:300]}")
_ensured.add(key)In your route, call ensure_ethora_user(...) for the signed-in user and return {"token": client_token(user_id)}, or 401 without a session.
Frontend: pass the token to jwtLogin
Fetch the token, then render the chat only once it exists. Pass the same memoized config to XmppProvider and Chat.
// EthoraChat.tsx — web, @ethora/chat-component (Vite env shown)
import { useEffect, useMemo, useState } from 'react';
import { Chat, XmppProvider } from '@ethora/chat-component';
import '@ethora/chat-component/dist/main.css';
export default function EthoraChat() {
const [token, setToken] = useState<string | null>(null);
useEffect(() => {
fetch('/api/ethora/token', { credentials: 'include' }).then((r) => r.json()).then((d) => setToken(d.token));
}, []);
const config = useMemo(() => ({
appId: import.meta.env.VITE_ETHORA_APP_ID,
customAppToken: import.meta.env.VITE_ETHORA_APP_TOKEN, // app token, "JWT eyJ…"
initBeforeLoad: true,
newArch: true,
refreshTokens: { enabled: true },
...(token ? { jwtLogin: { enabled: true, token } } : {}),
}), [token]);
if (!token) return null;
return (
<XmppProvider config={config}>
<Chat config={config} />
</XmppProvider>
);
}Without baseUrl and xmppSettings the component uses Ethora Cloud defaults; set them for a self-hosted server. React Native (@ethora/chat-component-rn) takes the same jwtLogin block; render <Chat config={config} /> without your own XmppProvider.
Token lifetimes and refresh
- Client JWT: you set
exp. Keep it to hours (the examples use 12 hours). WithrefreshTokens: { enabled: true }the SDK keeps its own session and needs a new client JWT only on a cold start. - Server JWT: mint one per request; the examples use 1 hour.
- Ethora user access token: 1 hour. If you hold user tokens yourself, refresh with
POST /v1/users/login/refresh, headerAuthorization: <refreshToken>, which returns{ token, refreshToken }. - When the Ethora session is gone for good, the chat shows its fallback screen: fetch a new client JWT and re-render.
Other auth modes
| Mode | Config | Use when |
|---|---|---|
| Client JWT (this page) | jwtLogin: { enabled: true, token } | Your app has its own users. Recommended. |
| Injected user | userLogin: { enabled: true, user } | Your backend already holds the full Ethora user object (token, refreshToken, xmppPassword, xmppUsername). |
| Custom async login | customLogin: { enabled: true, loginFunction } | Same, resolved by your function. |
| Email/password | user={{ email, password }} prop, or customAppToken + built-in form | Demos, or accounts that live in the Ethora app. |
googleLogin: { enabled: true, firebaseConfig } | Firebase Google sign-in (web). |
In @ethora/chat-component 26.9.x the built-in email form and the user prop send a hard-coded appId; use jwtLogin or customLogin instead.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
401 USER_NOT_FOUND at /v1/users/client | User was never created in the app | Call /v1/users/batch first. |
401/403 at /v1/users/client | Wrong or rotated secret, wrong appId, missing data.type: "client", expired exp | Copy the secret again from Settings → API; check the payload. |
422 VALIDATION_ERROR from /v1/users/batch | firstName or lastName empty or shorter than 2 characters | Split the name; fall back to User. |
400 APP_NOT_FOUND | App was deleted, or the ID belongs to another API host | Check the app ID and ETHORA_API_URL. |
INVALID_TOKEN_TYPE | A token of the wrong type for the endpoint | Use the token type the endpoint expects. |
Login screen appears although jwtLogin is set | Token was undefined on first render | Render Chat after the token arrives. |
Next steps
- Create rooms and add members from your backend
- REST API overview
- Interactive API reference: https://api.chat.ethora.com/api-docs/
Stuck or planning something bigger?
Book 15 minutes with the team, or open an issue on GitHub. Self-hosting and enterprise questions are welcome.