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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@chat21/chat21-node-sdk

v1.1.12

Published

Chat21 Nodejs SDK

Readme

@chat21/chat21-node-sdk

Node.js client for the REST APIs of Chat21, the messaging engine used by Tiledesk.

The package builds HTTP calls to a Chat21 backend. It does not open an MQTT or realtime connection. Every API URL has this shape:

{url}/api/{appid}{path}

In a Tiledesk installation that backend is chat21-http-server (default port 8004). The same client can target Firebase Cloud Functions by changing url and the token type.

Where it is used

tiledesk-server depends on this package in the Chat21 module, also published as @tiledesk/tiledesk-chat21-app. The client is created in channels/chat21/chat21Client.js with CHAT21_URL and CHAT21_APPID. channels/chat21/chat21Handler.js sets CHAT21_ADMIN_TOKEN and uses the SDK to:

  • send direct and group messages to agents
  • report typing
  • create, update, and fill groups (Tiledesk requests)
  • archive a conversation and delete its messages and timelines
  • create and update contacts on user signup and user update

The flow is described in Components: Chat21 is the messaging engine, Tiledesk Server is the application engine. Inbound events (a new message, a join, and so on) reach Tiledesk through webhooks from chat21-server. Outbound actions go through this SDK to chat21-http-server.

| Project | Repository | | --- | --- | | Tiledesk Server | https://github.com/Tiledesk/tiledesk-server | | Chat21 HTTP Server | https://github.com/chat21/chat21-http-server | | Deploy (Docker Compose / Helm) | https://github.com/Tiledesk/tiledesk-deployment |

chat21-http-server is public in the chat21 GitHub organization.

Installation

npm install @chat21/chat21-node-sdk
const Chat21 = require('@chat21/chat21-node-sdk');

Every method on messages, conversations, groups, contacts, and auth.signin returns a Promise.

Configuration

const chat21 = new Chat21({
  url: 'http://localhost:8004',   // backend base URL, without /api
  appid: 'tilechat',               // tenant. Tiledesk defaults to tilechat
  admintoken: process.env.CHAT21_ADMIN_TOKEN, // optional, see Authentication

  // only for auth.signin (Identity Toolkit / Firebase Auth REST)
  authurl: process.env.CHAT21_AUTH_URL,

  // only for firebaseAuth.signinWithCustomToken
  firebase_apikey: process.env.FIREBASE_APIKEY,
  firebase_database: process.env.FIREBASE_DATABASE,

  // set the Authorization header immediately, as an alternative to auth.*
  email: '[email protected]',
  password: 'secret',
  oauth: false,
  token: undefined
});

| Field | Effect | | --- | --- | | url | Required for the APIs. Native example: http://localhost:8004. Firebase example: https://<project>.cloudfunctions.net. | | appid | Path segment. Tiledesk uses tilechat. | | admintoken | When set, every call appends ?token=. | | email + password | Header Authorization: Basic .... | | oauth: true + token | Header Authorization: Bearer <token>. This header replaces Basic when both are set. | | authurl | URL of the auth.signin POST. It is not prefixed with /api/{appid}. |

tiledesk-server uses CHAT21_ENABLED, CHAT21_ENGINE (mqtt or firebase), CHAT21_URL, CHAT21_APPID, and CHAT21_ADMIN_TOKEN. The SDK selects the engine only through the URL and the token.

Authentication

chat21-http-server accepts the JWT in three places, in this order: the Authorization header, the jwt / JWT query parameter, the token query parameter. The admin role in the tiledesk_api_roles claim is what allows a call to act on behalf of another user (for example user_id when archiving).

Admin token

This is the mode used by tiledesk-server. The token is appended to every request as ?token=.

const chat21 = new Chat21({
  url: process.env.CHAT21_URL || 'http://localhost:8004',
  appid: process.env.CHAT21_APPID || 'tilechat'
});

chat21.auth.setAdminToken(process.env.CHAT21_ADMIN_TOKEN);

chat21.messages.sendToGroup(
  'Bot',
  'support-group-abc',
  'Request',
  'Hello',
  'bot-id',
  { tiledesk_message_id: '...' },
  'text',
  null,
  Date.now()
);

With CHAT21_ENGINE=mqtt the token is a JWT signed with CHAT21_JWT_SECRET (the same value as JWT_KEY on chat21-http-server). With CHAT21_ENGINE=firebase, Tiledesk points CHAT21_URL at Cloud Functions and uses that project's admin token.

admintoken can also be passed to the constructor. setAdminToken updates the same config shared by later calls.

User bearer token

To call the APIs as an already authenticated user:

const chat21 = new Chat21({
  url: 'http://localhost:8004',
  appid: 'tilechat',
  oauth: true,
  token: userJwt
});

// equivalent, after construction
chat21.auth.setCurrentToken(userJwt);
chat21.auth.getCurrentToken();
chat21.auth.logout(); // clears authorization, token, and user_id

On chat21-http-server, Authorization may be the raw JWT. The SDK always sends the Bearer prefix.

Email and password

In the constructor, email and password produce a Basic header. The actual login is auth.signin, which POSTs { email, password, returnSecureToken: true } to authurl. When the response contains idToken and localId, the header is replaced with Bearer <idToken>.

const chat21 = new Chat21({
  url: 'http://localhost:8004',
  appid: 'tilechat',
  authurl: process.env.CHAT21_AUTH_URL
});

const session = await chat21.auth.signin('[email protected]', 'secret');
// session.idToken, session.localId

That response shape is the Firebase Identity Toolkit format. The native JWT is issued by tiledesk-server (createCustomToken in the Chat21 channel).

Firebase custom token

firebaseAuth exchanges a Firebase custom token for an ID token. That ID token then has to be set as the bearer token. This path requires firebase_apikey and firebase_database, and it initializes the firebase client SDK at startup.

const idToken = await chat21.firebaseAuth.signinWithCustomToken(customAuthToken);
chat21.auth.setCurrentToken(idToken);

API

The JSON body is sent as built. Omitted fields (null, undefined, or absent) stay out of the payload, except where noted. When an admin token is configured, the token query parameter is appended to the path.

Network errors reject the Promise. An HTTP error status still resolves the Promise with the body: the client does not check the status code.

messages

POST /api/{appid}/messages

chat21.messages.send(
  senderFullname,
  recipientId,          // user id for direct, group id for a group
  recipientFullname,
  text,
  senderId,             // optional
  attributes,           // optional object
  type,                 // optional, e.g. "text" | "image"
  metadata,             // optional, e.g. { src, width, height } for images
  group                 // optional
);

sendToGroup uses the same endpoint. timestamp takes the place of group as the second-to-last argument. It always sets channel_type: "group". A message without channel_type is a direct message.

chat21.messages.sendToGroup(
  senderFullname,
  groupId,
  recipientFullname,
  text,
  senderId,
  attributes,
  type,
  metadata,
  timestamp,            // optional
  group                 // optional
);

delete(recipientId) calls DELETE /api/{appid}/{recipientId}/messages/timelines and removes that conversation's messages from the timelines.

conversations

| Method | HTTP | Notes | | --- | --- | --- | | archive(recipientId, userId) | DELETE /api/{appid}/conversations/{recipientId} | Body { user_id } when userId is passed. On chat21-http-server an admin can archive on behalf of that user; otherwise the JWT user is used. | | delete(recipientId) | DELETE /api/{appid}/{recipientId}/conversations/timelines | Deletes conversations with that recipient from every timeline. | | typing(recipientId, writerId, text, timestamp) | PUT /api/{appid}/typings/{recipientId} | Optional body fields: writer_id, text, timestamp. Used by tiledesk-server on outbound group messages. | | stopTyping(recipientId, writerId) | DELETE /api/{appid}/typings/{recipientId} | Present in the client. Marked in the source as deprecated and unused. |

typing and stopTyping have no route on the current chat21-http-server. They stay in the client because the Firebase channel and tiledesk-server call them.

groups

members is an array of user ids. The client maps it to the object the API expects, { "<userId>": 1 }.

| Method | HTTP | | --- | --- | | create(name, members, attributes, groupId) | POST /api/{appid}/groups | | join(memberId, groupId) | POST /api/{appid}/groups/{groupId}/members | | leave(memberId, groupId) | DELETE /api/{appid}/groups/{groupId}/members/{memberId} | | setMembers(members, groupId) | PUT /api/{appid}/groups/{groupId}/members | | update(name, owner, attributes, groupId) | PUT /api/{appid}/groups/{groupId} | | updateAttributes(attributes, groupId) | PUT /api/{appid}/groups/{groupId}/attributes | | delete(groupId) | DELETE /api/{appid}/groups/{groupId} |

create sends group_name, group_members, group_id, and attributes when present. update sends group_name, group_owner, and attributes. On chat21-http-server a group update requires group_name. That server exposes join, leave, set members, update, and update attributes. It does not expose deletion of the whole group.

const created = await chat21.groups.create(
  'Support',
  ['user-1', 'user-2'],
  { source: 'tiledesk' },
  'support-group-abc'
);

await chat21.groups.join('user-3', 'support-group-abc');
await chat21.groups.setMembers(['user-1', 'user-3'], 'support-group-abc');
await chat21.groups.updateAttributes({ status: 100 }, 'support-group-abc');
await chat21.groups.leave('user-1', 'support-group-abc');

contacts

| Method | HTTP | Body | | --- | --- | --- | | create(firstname, lastname, email, currentUser) | POST /api/{appid}/contacts | firstname, lastname, email, current_user | | update(firstname, lastname, currentUser) | PUT /api/{appid}/contacts/me | firstname, lastname, current_user |

tiledesk-server calls these on user.signup and user.update. chat21-http-server resolves contacts for reads through CONTACTS_LOOKUP_ENDPOINT. The contact routes belong to the historical Firebase backend.

auth

| Method | Effect | | --- | --- | | signin(email, password) | Logs in against authurl and stores the bearer token, token, and user_id. | | logout() | Clears authorization, token, and user_id. It does not revoke the token on the server. | | getCurrentToken() / setCurrentToken(token) | Reads or sets the user bearer token. | | getAdminToken() / setAdminToken(token) | Reads or sets the admin token (?token=). |

Logging

The client logs with Winston to the console and to logs/chat21.log (5 MB rotation, 5 files) at level info. At startup, when Basic or Bearer auth is configured, the Authorization header value is logged.

Tests

npm test

Mocha loads CHAT21_URL, CHAT21_APPID, CHAT21_AUTH_URL, FIREBASE_APIKEY, and FIREBASE_DATABASE from .env and calls a real backend. These are integration tests.

License

See LICENSE.