SDK
SDK Authentication
Authenticate SDK connections with JWT tokens, handle token refresh, and manage session lifecycle.
The SDK authenticates via JWT tokens passed during client initialization. The token is used for both HTTP API calls and WebSocket connections.
Connecting with a Token
import { RealtimeClient } from '@smarterservices/realtime';
const realtime = new RealtimeClient({
url: 'http://localhost:3000',
token: 'your-jwt-token',
});The token is attached to the WebSocket handshake and all subsequent HTTP requests.
Obtaining a Token
Tokens are issued by the platform's auth endpoint:
curl -X POST http://localhost:3000/auth/token \
-H 'Content-Type: application/json' \
-d '{
"applicationId": "your-app-id",
"permissions": ["subscribe", "publish"]
}'The response contains a signed JWT:
{
"token": "eyJhbGciOiJIUzI1NiIs...",
"expiresAt": 1710003600000
}Token Structure
JWT tokens contain:
| Claim | Description |
|---|---|
sub | Subject (user or service ID) |
aud | Audience (application ID) |
iss | Issuer |
exp | Expiration timestamp |
iat | Issued-at timestamp |
kid | Key ID (for key rotation) |
permissions | Array of granted permissions |
Token Helpers
The SDK includes utility functions for token inspection:
import { decodeToken, isTokenExpired, getTokenExpiresIn, shouldRefreshToken } from '@smarterservices/realtime';
const decoded = decodeToken(token);
console.log(decoded.sub); // User ID
if (isTokenExpired(token)) {
console.log('Token has expired');
}
const expiresIn = getTokenExpiresIn(token);
console.log(`Expires in ${expiresIn}ms`);
if (shouldRefreshToken(token)) {
// Token is close to expiring, refresh it
}Permission Roles
Tokens can carry one of three permission levels:
| Role | Capabilities |
|---|---|
admin | Full access — manage topics, schemas, keys, users |
service | Publish events, manage documents, broadcast |
client | Subscribe to topics, read documents |
Error Handling
realtime.on('error', (err) => {
if (err.code === 'AUTH_FAILED') {
console.log('Authentication failed — token may be expired or invalid');
// Obtain a new token and reconnect
}
});Verifying a Token
Server-side token verification:
curl -X POST http://localhost:3000/auth/verify \
-H 'Content-Type: application/json' \
-d '{ "token": "eyJhbGciOiJIUzI1NiIs..." }'Returns the decoded claims if valid, or a 401 error if invalid/expired.