Client SDK (@messagejs/client)
Relevant source files
The following files were used as context for generating this wiki page:The @messagejs/client package is a lightweight, frontend-focused SDK for both browsers and Node.js environments. Its primary purpose is to provide a simple and secure way for web applications to send messages through various platforms (like WhatsApp, Telegram, etc.) via the MessageJS backend API. It is designed to be similar to the EmailJS API, abstracting away backend complexities and preventing the exposure of sensitive connector credentials on the client-side.
This SDK is a key component of the MessageJS monorepo, acting as the main entry point for developers to integrate MessageJS into their applications. It handles configuration, API communication, and error handling for sending templated messages.
Sources: README.md:14-16 an 34-37, packages/client/package.json:5, packages/client/src/index.ts:3-6, QUICK_START.md:9-14
Installation
The SDK can be integrated into a project using either a package manager or a CDN for direct browser usage.
npm/yarn
npm install @messagejs/client
# or
yarn add @messagejs/client
CDN (Browser)
<script src="https://cdn.messagejs.pro/v1/messagejs.js"></script>
Sources: QUICK_START.md:66-73, packages/client/package.json:2
Core Architecture
The SDK is built around a single MessageJS class, which manages the API key and base URL configuration. For ease of use, a singleton instance named messagejs is exported, which should be used to access all SDK functionality.
Sources: packages/client/src/index.ts:80-89
Class Diagram
This diagram shows the structure of the MessageJS class, its private properties, and public methods.
Sources: packages/client/src/index.ts:71-125
Initialization
Before sending any messages, the SDK must be initialized with a project's API key. This is done using the init() method. An optional configuration object can be provided to specify a custom API endpoint, which is useful for self-hosted instances.
import { messagejs } from '@messagejs/client';
// Initialize with just the API key
messagejs.init('sk_live_abc123def456...');
// Or with a full configuration object
messagejs.init({
apiKey: 'sk_live_abc123def456...',
baseUrl: 'https://api.messagejs.pro/v1' // Default value
});
The init method accepts either a string (the API key) or a MessageJSConfig object.
| Parameter | Type | Description |
|---|---|---|
apiKey | string | Required. The public API key for your MessageJS project. |
baseUrl | string | Optional. The base URL of the MessageJS API. Defaults to https://api.messagejs.pro/v1. |
Sources: packages/client/src/index.ts:13-26 an 91-104, QUICK_START.md:78-87
Sending Messages
The primary function of the SDK is the sendMessage method. It sends a request to the MessageJS backend to dispatch a message using a pre-configured connector and template.
Data Flow
The sendMessage method constructs and sends a POST request to the /api/v1/messages endpoint. The API key is passed in the Authorization header as a Bearer token. If the request is successful, the backend queues the message for sending and returns a confirmation.
sendMessage Parameters (SendParams)
The sendMessage method takes a single object with the following properties, defined by the SendParams interface.
| Parameter | Type | Description |
|---|---|---|
connectorId | string | Required. The ID of the connector to use for sending. |
templateId | string | Required. The ID of the template to use. |
to | string | Required. The recipient's identifier (e.g., E.164 phone number). |
variables | Record<string, any> | Required. Key-value pairs to replace variables in the template. |
metadata | Record<string, any> | Optional. Metadata to associate with the message for logging/tracking. |
Sources: packages/client/src/index.ts:31-52, packages/core/src/types/apiTypes.ts:39-46
sendMessage Return Value (SendResult)
The method returns a Promise that resolves to a SendResult object upon successful API validation. If the API call fails (e.g., network error, invalid API key), the promise is rejected.
| Property | Type | Description |
|---|---|---|
messageId | string | The unique ID of the message log created by the API. |
status | string | The initial status of the message, typically queued. |
error | string | Optional. An error message if the API request failed validation. |
A successful API call returns a 202 Accepted status, indicating the message is queued. The status field in the response reflects this.
Sources: packages/client/src/index.ts:57-70, packages/core/src/api/controllers/messageController.ts:55-60
Example Usage
async function sendWelcomeMessage() {
try {
const result = await messagejs.sendMessage({
to: '+1234567890',
connectorId: 'conn_whatsapp', // From your dashboard
templateId: 'tpl_welcome', // From your dashboard
variables: {
name: 'John',
code: '12345'
}
});
console.log('Message queued successfully!', result.messageId);
} catch (error) {
console.error('Failed to send message:', error.message);
}
}
Sources: QUICK_START.md:93-105, packages/client/src/index.ts:106-125
Packaging and Distribution
The @messagejs/client package is configured to support both modern ESM import and legacy CommonJS require syntax. The build process, managed by Rollup, compiles the TypeScript source into multiple formats.
The key output files in the dist/ directory are:
index.js: The ES module entry point.index.cjs: The CommonJS entry point.index.d.ts: The TypeScript declaration file for type support.
This dual-module setup ensures broad compatibility across different JavaScript environments.
Sources: packages/client/package.json:6-14