npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@tegrabox/chat-sdk

v1.0.4

Published

TypeScript SDK for Chat API with REST and WebSocket support

Readme

Chat SDK

TypeScript SDK for the Chat API with REST and WebSocket support. Designed for backend/server-side use with your project API key.

Installation

npm install @tegrabox/chat-sdk

Use Cases

Backend/Server-side: Use this SDK in your backend to:

  • Manage users, rooms, and messages
  • Generate JWT tokens for your frontend clients
  • Handle server-side chat operations

Client-side: Your frontend apps should:

  • Use JWT tokens (generated by your backend) for WebSocket connections
  • Make REST API calls through your backend (not directly with API keys)

⚠️ Security: Never expose your API key in client-side code. Keep it secure on your backend.

Quick Start

Backend (with API Key)

import ChatClient from '@tegrabox/chat-sdk';

// Initialize with API key for project-level operations
const client = new ChatClient({
  apiKey: process.env.CHAT_API_KEY, // Store in environment variables
});

// Create a user
const user = await client.users.create({
  username: 'johndoe',
  external_user_id: 'user_12345',
  display_name: 'John Doe',
});

// Generate JWT token for frontend client
const tokenResponse = await client.users.generateToken(user.id);
// Send tokenResponse.token to your frontend

// Create a room
const room = await client.rooms.create({
  name: 'General Chat',
  created_by: user.id, // User automatically added as member
});

// Send a message (server-side)
const message = await client.messages.create(room.id, {
  content: 'Hello, world!',
  user_id: user.id,
});

Frontend (with JWT Token)

import ChatClient from '@tegrabox/chat-sdk';

// Initialize with JWT token (received from your backend)
const client = new ChatClient({
  jwtToken: 'your_jwt_token_from_backend',
});

// Use WebSocket for real-time messaging
client.socket.connect();
client.socket.joinRoom('room-id');

// Verify token
const authInfo = await client.auth.verify();
console.log('User ID:', authInfo.user.userId);

Authentication

The SDK supports two authentication methods:

API Key (Project-Level Operations)

Use API key for managing users, rooms, and messages. Keep this secret—use environment variables:

// Backend initialization
const client = new ChatClient({
  apiKey: process.env.CHAT_API_KEY, // Never hardcode!
});

// The SDK automatically:
// - Fetches your project ID from the backend
// - Caches it for all subsequent calls
// - Handles authentication headers

Required for:

  • Users API (create, list, update, delete, generateToken)
  • Rooms API (create, list, update, delete)
  • Messages API (create, delete)

JWT Token (User-Level Operations)

Use JWT token for user-specific operations like WebSocket and auth verification:

// Frontend initialization (token from your backend)
const client = new ChatClient({
  jwtToken: 'your_jwt_token_here',
});

// Or initialize with both (backend that also needs WebSocket)
const client = new ChatClient({
  apiKey: process.env.CHAT_API_KEY,
  jwtToken: 'jwt_token_for_websocket',
});

Required for:

  • WebSocket connections
  • Auth API (verify)

Note: You can initialize with either apiKey OR jwtToken OR both, depending on what operations you need.

API Reference

Users

// Create
const user = await client.users.create({
  username: 'johndoe',
  external_user_id: 'user_12345',
  display_name: 'John Doe',
  email: '[email protected]', // optional
});

// List
const result = await client.users.list({ page: 1, limit: 50 });
console.log(result.items); // ChatUser[]
console.log(result.total); // number

// Get
const user = await client.users.get('user-id');

// Update
const updated = await client.users.update('user-id', {
  display_name: 'New Name',
  status: 'active',
});

// Generate JWT token
const tokenResponse = await client.users.generateToken('user-id');

// Revoke tokens
await client.users.revokeToken('user-id');

// Delete
await client.users.delete('user-id');

Rooms

// List
const result = await client.rooms.list({ page: 1, limit: 20 });

// Create (created_by user is automatically added as member)
const room = await client.rooms.create({
  name: 'General Chat',
  created_by: 'user-id', // Required
});

// Get
const room = await client.rooms.get('room-id');

// Join
await client.rooms.join('room-id');

// Leave
await client.rooms.leave('room-id');

// Update (returns 501 - coming soon)
await client.rooms.update('room-id', { name: 'New Name' });

// Delete (returns 501 - coming soon)
await client.rooms.delete('room-id');

Messages

// List
const result = await client.messages.list('room-id', {
  page: 1,
  limit: 50,
});

// Create
const message = await client.messages.create('room-id', {
  content: 'Hello!',
  user_id: 'user-id', // Required
});

// Delete (returns 501 - coming soon)
await client.messages.delete('room-id', 'message-id');

Auth

// Verify JWT token
const authInfo = await client.auth.verify();
console.log(authInfo.user.userId);

WebSocket

Real-time messaging with Socket.io. Note: WebSocket can be used from backend or frontend, but frontend should use JWT tokens (not API keys).

Backend Usage

// Generate token for a user
const tokenResponse = await client.users.generateToken('user-id');
client.setJwtToken(tokenResponse.token);

// Connect
client.socket.connect();

// Join room
client.socket.joinRoom('room-id');

// Listen for messages
client.socket.onMessage((message) => {
  console.log(`${message.username}: ${message.content}`);
});

// Send message
client.socket.sendMessage('room-id', 'Hello!');

// Disconnect
client.socket.disconnect();

Frontend Usage (with JWT token from backend)

// Your backend provides the JWT token
const jwtToken = await fetch('/api/chat/token').then((r) => r.json());

// Initialize client with JWT token only (no API key needed)
const client = new ChatClient({ jwtToken: jwtToken.token });

// Connect and use WebSocket
client.socket.connect();
client.socket.joinRoom('room-id');
client.socket.onMessage((message) => {
  console.log(`${message.username}: ${message.content}`);
});

WebSocket Events

Client → Server:

  • joinRoom(roomId) - Join a room
  • leaveRoom(roomId) - Leave a room
  • sendMessage(roomId, content) - Send a message
  • startTyping(roomId) - Start typing indicator
  • stopTyping(roomId) - Stop typing indicator

Server → Client:

  • onMessage(callback) - Receive messages
  • onUserJoined(callback) - User joined event
  • onUserLeft(callback) - User left event
  • onUserTyping(callback) - User typing event
  • onUserStoppedTyping(callback) - User stopped typing event
  • onError(callback) - Error event
  • onConnect(callback) - Connection established
  • onDisconnect(callback) - Disconnection event

Error Handling

import {
  AuthenticationError,
  NotFoundError,
  ValidationError,
  NetworkError,
} from '@tegrabox/chat-sdk';

try {
  await client.users.create({ username: 'test', external_user_id: '123' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    // Invalid API key
  } else if (error instanceof ValidationError) {
    // Invalid input
  } else if (error instanceof NetworkError) {
    // Network issue
  }
}

Error Types:

  • AuthenticationError - 401/403 (invalid API key or token)
  • NotFoundError - 404 (resource not found)
  • ValidationError - 400 (invalid input)
  • ConflictError - 409 (resource conflict)
  • ServerError - 5xx (server error)
  • NetworkError - Network/fetch errors
  • WebSocketError - WebSocket-specific errors

Configuration

interface ChatClientOptions {
  baseUrl?: string; // Optional - defaults to https://chat-server-psq1.onrender.com
  /**
   * API Key for project-level operations (managing users, rooms, messages).
   * Required for: Users API, Rooms API, Messages API
   * Keep this secret - use environment variables in production.
   */
  apiKey?: string;
  /**
   * JWT Token for user-level operations (WebSocket, auth verification).
   * Required for: WebSocket connections, Auth API
   * Generate tokens using UsersAPI.generateToken() with API key.
   */
  jwtToken?: string;
}

// Example: Backend initialization (with API key)
const client = new ChatClient({
  apiKey: process.env.CHAT_API_KEY, // Store securely!
  baseUrl: process.env.CHAT_BASE_URL, // Optional
});

// Example: Frontend initialization (with JWT token only)
const frontendClient = new ChatClient({
  jwtToken: 'jwt-token-from-backend',
});

// Example: Backend with WebSocket (both)
const fullClient = new ChatClient({
  apiKey: process.env.CHAT_API_KEY,
  jwtToken: 'jwt-token-for-websocket',
});

// Update base URL (if needed)
client.setBaseUrl('https://custom-server.com');

// Update JWT token (for WebSocket)
client.setJwtToken('jwt-token-from-backend');

Note: At least one of apiKey or jwtToken must be provided. Use apiKey for project-level operations, jwtToken for user-level operations, or both for full functionality.

Pagination

interface PaginationParams {
  page?: number; // Default: 1
  limit?: number; // Default varies by endpoint
}

const result = await client.users.list({ page: 1, limit: 50 });
// result.items - ChatUser[]
// result.page - current page
// result.total - total items
// result.totalPages - total pages

TypeScript

Full type definitions included:

import type {
  ChatUser,
  Room,
  Message,
  CreateUserInput,
  CreateRoomInput,
  CreateMessageInput,
  UpdateRoomInput,
  PaginatedResponse,
} from '@tegrabox/chat-sdk';

Requirements

  • Node.js >= 18.0.0
  • TypeScript >= 5.0.0 (recommended)

React Native / Browser Support

The SDK works in React Native and browser environments, but API key should only be used server-side.

Recommended Architecture

┌─────────────┐         ┌──────────────┐         ┌─────────────┐
│   Frontend  │────────▶│   Backend    │────────▶│  Chat API   │
│  (React/RN) │  JWT    │  (Node.js)   │  API    │             │
│             │◀────────│              │  Key    │             │
└─────────────┘         └──────────────┘         └─────────────┘

Backend (uses SDK with API key):

  • Manages users, rooms, messages
  • Generates JWT tokens for frontend
  • Handles server-side operations

Frontend (uses JWT tokens):

  • Receives JWT token from your backend
  • Uses WebSocket with JWT token for real-time features
  • Makes REST calls through your backend API

Demo App

See demo/react-native/ for a complete example app. Note: The demo uses API keys directly for testing purposes only. In production, your backend should handle API key operations.

License

MIT