Keep Members Online From Your App
If your team works in your own app instead of DashX, for example an internal console where agents handle customers, that app can keep each member online in DashX while they have it open. Assignment rules set to Only assign to people who are online? then hand those members issues, with no DashX tab open in the background.
Your backend mints a member token for the member who is signed in to your app, and the JavaScript SDK connects with it. Nobody has to set a status by hand, and your app sends nothing else.
How it works
- While your app's connection is open, the member counts as Online, as they would with a DashX tab open.
- When they close your app, they go Offline about 30 seconds later. A page reload or a short network drop within that time doesn't take them offline.
- If their connection is lost without closing, as when a laptop sleeps or the network goes down, assignment rules stop giving them issues within about 35 seconds. Their status can take up to a minute and a half to change to Offline for others.
- The member's own status still applies. If they set Away or Busy in DashX, that's what others see, and Invisible shows them as offline. Assignment rules skip all three.
- Ready for Work is still turned on from the member's status menu in DashX. A rule set to Only assign to people who are ready for work? needs that too.
- A member token only keeps the member online. It doesn't sign them in to DashX, read your data, or deliver their notifications.
1. Mint a member token on your backend
Mint the token on your backend with your workspace's Private Key, and never send the Private Key to the browser. Use the key pair whose Public Key your app connects with in step 2. Pass the member's email address or their DashX account id, and DashX signs a token for that member:
- Node.js
- Spring Boot (Java)
- Python
- Ruby
- API
const response = await fetch('https://api.dashx.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Public-Key': '<YOUR PUBLIC KEY>',
'X-Private-Key': '<YOUR PRIVATE KEY>',
},
body: JSON.stringify({
query: 'query ($input: GenerateIdentityTokenInput!) { generateIdentityToken(input: $input) { token } }',
variables: {
input: {
publicKey: '<YOUR PUBLIC KEY>',
privateKey: '<YOUR PRIVATE KEY>',
kind: 'MEMBER',
uid: 'agent@example.com',
},
},
}),
});
const { data, errors } = await response.json();
if (errors) {
throw new Error(errors[0].message);
}
const memberToken = data.generateIdentityToken.token;
String memberToken = dashX.generateMemberToken("agent@example.com").get();
Requires the Java SDK 1.7.0 or later. It fails with a DashXException carrying the reason below.
import requests
response = requests.post(
'https://api.dashx.com/graphql',
headers={
'X-Public-Key': '<YOUR PUBLIC KEY>',
'X-Private-Key': '<YOUR PRIVATE KEY>',
},
json={
'query': 'query ($input: GenerateIdentityTokenInput!) { generateIdentityToken(input: $input) { token } }',
'variables': {
'input': {
'publicKey': '<YOUR PUBLIC KEY>',
'privateKey': '<YOUR PRIVATE KEY>',
'kind': 'MEMBER',
'uid': 'agent@example.com',
},
},
},
)
body = response.json()
if body.get('errors'):
raise Exception(body['errors'][0]['message'])
member_token = body['data']['generateIdentityToken']['token']
require 'json'
require 'net/http'
response = Net::HTTP.post(
URI('https://api.dashx.com/graphql'),
{
query: 'query ($input: GenerateIdentityTokenInput!) { generateIdentityToken(input: $input) { token } }',
variables: {
input: {
publicKey: '<YOUR PUBLIC KEY>',
privateKey: '<YOUR PRIVATE KEY>',
kind: 'MEMBER',
uid: 'agent@example.com'
}
}
}.to_json,
'Content-Type' => 'application/json',
'X-Public-Key' => '<YOUR PUBLIC KEY>',
'X-Private-Key' => '<YOUR PRIVATE KEY>'
)
body = JSON.parse(response.body)
raise body['errors'][0]['message'] if body['errors']
member_token = body.dig('data', 'generateIdentityToken', 'token')
query ($input: GenerateIdentityTokenInput!) {
generateIdentityToken(input: $input) {
token
}
}
Send it to https://api.dashx.com/graphql with your X-Public-Key and X-Private-Key headers, and these variables:
{
"input": {
"publicKey": "<YOUR PUBLIC KEY>",
"privateKey": "<YOUR PRIVATE KEY>",
"kind": "MEMBER",
"uid": "agent@example.com"
}
}
The token lasts 12 hours. Minting fails if no enabled member of your workspace has that email or id. Member emails are unique only within an environment, so it also fails if two enabled members share the email; pass the account id instead.
Sign it yourself
You can also sign the token yourself, as you do for user identity tokens: an HS256 JWT signed with your Private Key. A member token's payload has these keys:
kind:MEMBERuid: the member's DashX account idenvironment_id: the id of the environment that member account belongs toiat: when you issued the token (UNIX timestamp)exp: when it expires (UNIX timestamp), afteriatand at most 24 hours later
- Node.js
- Spring Boot (Java)
- Python
- Ruby
const jwt = require('jsonwebtoken');
const issuedAt = Math.floor(Date.now() / 1000);
const memberToken = jwt.sign({
kind: 'MEMBER',
uid: '<MEMBER ACCOUNT ID>',
environment_id: '<ENVIRONMENT ID>',
iat: issuedAt,
exp: issuedAt + 12 * 60 * 60, // 12 hours
}, '<YOUR PRIVATE KEY>');
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.nio.charset.StandardCharsets;
import java.util.Date;
Date issuedAt = new Date();
String memberToken = Jwts.builder()
.claim("kind", "MEMBER")
.claim("uid", "<MEMBER ACCOUNT ID>")
.claim("environment_id", "<ENVIRONMENT ID>")
.issuedAt(issuedAt)
.expiration(new Date(issuedAt.getTime() + 12 * 60 * 60 * 1000L)) // 12 hours
.signWith(Keys.hmacShaKeyFor("<YOUR PRIVATE KEY>".getBytes(StandardCharsets.UTF_8)), Jwts.SIG.HS256)
.compact();
This uses JJWT 0.12: io.jsonwebtoken:jjwt-api, with jjwt-impl and jjwt-jackson at runtime.
import time
import jwt
issued_at = int(time.time())
member_token = jwt.encode({
'kind': 'MEMBER',
'uid': '<MEMBER ACCOUNT ID>',
'environment_id': '<ENVIRONMENT ID>',
'iat': issued_at,
'exp': issued_at + 12 * 60 * 60, # 12 hours
}, '<YOUR PRIVATE KEY>', algorithm='HS256')
require 'jwt'
issued_at = Time.now.to_i
member_token = JWT.encode({
kind: 'MEMBER',
uid: '<MEMBER ACCOUNT ID>',
environment_id: '<ENVIRONMENT ID>',
iat: issued_at,
exp: issued_at + 12 * 60 * 60 # 12 hours
}, '<YOUR PRIVATE KEY>', 'HS256')
To find a member's account id and environment id, decode a token minted for them above: its uid and environment_id hold both.
A token without iat, one issued in the future, or one that lasts longer than 24 hours is refused, so a leaked token stops working within a day.
2. Connect from your app
On your backend, add an endpoint that mints a token, as in step 1, for the member signed in to your app, and returns it, for example as { "token": "..." }. Your app calls that endpoint whenever it needs a token: pass a function that does so as identityTokenProvider, and connect.
- JavaScript
- React
import DashX from '@dashx/browser'
// Calls your backend, which mints a member token for the member signed in to your app.
async function fetchMemberToken() {
const response = await fetch('https://api.your-app.com/dashx/member-token', {
credentials: 'include',
})
if (!response.ok) {
throw new Error(`Could not get a member token: ${response.status}`)
}
const { token } = await response.json()
return token
}
const member = DashX.createClient({
publicKey: '<YOUR PUBLIC KEY>',
targetEnvironment: '<ENVIRONMENT>',
identityTokenProvider: fetchMemberToken,
})
member.connectWebSocket()
Call disconnectWebSocket() when the member signs out of your app. They go offline about 30 seconds later, as they would after closing it.
Use a separate client for the member. A client with identityTokenProvider keeps its identity in memory and never touches the identity your app sets for its own users with setIdentity, so the two can run on the same page.
import { DashXProvider } from '@dashx/react'
// Calls your backend, which mints a member token for the member signed in to your app.
async function fetchMemberToken() {
const response = await fetch('https://api.your-app.com/dashx/member-token', {
credentials: 'include',
})
if (!response.ok) {
throw new Error(`Could not get a member token: ${response.status}`)
}
const { token } = await response.json()
return token
}
<DashXProvider
publicKey="<YOUR PUBLIC KEY>"
targetEnvironment="<ENVIRONMENT>"
identityTokenProvider={fetchMemberToken}
initializeWebSocketOnLoad
>
<App />
</DashXProvider>
DashXProvider configures the app's main DashX client. If your app already uses it for its own users, create the member's client with DashX.createClient, as in the JavaScript tab, instead.
Set targetEnvironment to the environment your members belong to, usually your live environment. A member token is refused on a connection to any other environment.
The client takes care of the token from there:
- It calls
identityTokenProviderbefore it connects, and again about five minutes before each token expires, reconnecting with the new one. The member stays online throughout. - If DashX refuses a token, the client fetches one fresh token and tries again.
- If the provider fails, or the fresh token is refused too, the client stops. Call
connectWebSocket()again to start over with a new token.
You can also set the token yourself with setIdentity(undefined, token) before calling connectWebSocket(). Your app must then set a new token before the current one expires; the client reconnects with it. If a token expires first, the member goes offline until your app sets a new one.
Only do this in an app that sets no other DashX identity. Without a provider, the client keeps the token in the browser's local storage, which every DashX client on the page shares, so it would replace the identity token your app sets for its own users.
3. Let members go offline
Members go offline when they close your app. To let them step away while it stays open, give them a switch in your app, or have them set a status in DashX.
With a switch in your app
Disconnect to take the member offline, and connect to bring them back:
- JavaScript
- React
function setOnline(online) {
if (online) {
member.connectWebSocket()
} else {
member.disconnectWebSocket()
}
}
import { useDashXProvider } from '@dashx/react'
function OnlineSwitch({ online, onChange }) {
const dashx = useDashXProvider()
const toggle = () => {
if (online) {
dashx.disconnectWebSocket()
} else {
dashx.connectWebSocket()
}
onChange(!online)
}
return <button onClick={toggle}>{online ? 'Go offline' : 'Go online'}</button>
}
They show as Offline about 30 seconds after you disconnect, and assignment rules stop giving them issues. Coming back fetches a fresh token if the token has expired.
Every tab of your app has its own connection, and so does every DashX tab. A member stays online while any of them is connected, so a switch only takes them offline if it applies in every tab. The client doesn't remember the choice either. Keep it in local storage, so tabs opened later read it on load, and broadcast it to the tabs already open:
const channel = new BroadcastChannel('dashx-member-presence')
function applyOnline(online) {
if (online) {
member.connectWebSocket()
} else {
member.disconnectWebSocket()
}
}
function setOnline(online) {
localStorage.setItem('dashx-member-online', String(online))
channel.postMessage(online)
applyOnline(online)
}
channel.onmessage = (event) => applyOnline(event.data)
applyOnline(localStorage.getItem('dashx-member-online') !== 'false')
An open DashX tab keeps them online too, so they close it as well, or use a status in DashX instead.
With a status in DashX
The status a member sets in DashX belongs to their account, not to a tab, so it applies while your app is connected too:
- Invisible shows them as Offline, and assignment rules skip them.
- Away or Busy shows that status, and assignment rules skip them too.
- Turning off Ready for Work stops assignment from rules set to Only assign to people who are ready for work?
The status stays until they change it back in DashX, even if they close and reopen your app. They don't need to keep a DashX tab open afterwards.
Requirements
@dashx/browser0.15.1 or later@dashx/react0.6.0 or later, if you useDashXProvider- Java SDK 1.7.0 or later, if you mint tokens with
generateMemberToken
Troubleshooting
If a member stays offline while your app is open, the connection was most likely refused. Check that:
- the member's account is enabled
- the token's
kindisMEMBERand itsuidis the member's account id environment_idand the client'stargetEnvironmentare both the environment the member belongs to- a token you sign yourself has an
iat, and itsexpis afteriatand no more than 24 hours later - the token was minted or signed with the Private Key from the same key pair as the Public Key the client uses