sse-client-auth-onewise
v1.0.6
Published
A simple SSE client with accessToken authentication
Maintainers
Readme
sse-client-auth-onewise
A lightweight and easy-to-use SSE (Server-Sent Events) client for Node.js with built-in authentication support via query parameters.
This library provides a simple way to connect to SSE servers that require authentication through accessToken and optional roomId parameters. Perfect for real-time applications that need secure event streaming.
✨ Features
- 🔐 Authentication Support - Automatic handling of accessToken and roomId
- 🚀 Simple API - Easy to integrate with just a few lines of code
- 📡 Real-time Events - Efficient SSE connection management
- 🛡️ Error Handling - Built-in connection error management
- 📦 Lightweight - Minimal dependencies
- 🔄 Auto Reconnection - Automatic reconnection on connection loss
📦 Installation
npm install sse-client-auth-onewise🚀 Quick Start
const createSSEClient = require('sse-client-auth-onewise');
// Create SSE client with authentication
const sseClient = createSSEClient({
url: 'https://chatapi.onewise.app/bot-listen',
accessToken: 'your_access_token_here',
roomId: 'room_123', // optional
onMessage: (data) => {
console.log('📩 Received message:', data);
},
});
// The client will automatically connect and start listening for events📚 API Reference
createSSEClient(options)
Creates and returns a new SSE client instance.
Parameters
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| url | string | ✅ | The SSE server endpoint URL |
| accessToken | string | ✅ | Authentication token sent as query parameter |
| roomId | string | ❌ | Optional room/channel identifier |
| onMessage | function | ✅ | Callback function to handle incoming messages |
| onError | function | ❌ | Optional callback for error handling |
| onOpen | function | ❌ | Optional callback when connection opens |
Example with all options
const sseClient = createSSEClient({
url: 'https://chatapi.onewise.app/bot-listen',
accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
roomId: 'chat-room-456',
onMessage: (data) => {
try {
const parsed = JSON.parse(data);
console.log('📦 Parsed data:', parsed);
} catch (error) {
console.log('📝 Raw message:', data);
}
},
onError: (error) => {
console.error('❌ SSE Error:', error);
},
onOpen: () => {
console.log('✅ SSE Connection established');
}
});🔧 Usage Examples
Basic Chat Application
const createSSEClient = require('sse-client-auth-onewise');
const chatClient = createSSEClient({
url: 'https://chatapi.onewise.app/bot-listen',
accessToken: process.env.ACCESS_TOKEN,
roomId: 'general',
onMessage: (message) => {
try {
const chatMessage = JSON.parse(message);
// Message format: { text: "Hello!", attachments: [] }
console.log(`💬 Message: ${chatMessage.text}`);
// Handle attachments if present
if (chatMessage.attachments && chatMessage.attachments.length > 0) {
console.log(`📎 Attachments: ${chatMessage.attachments.length} file(s)`);
chatMessage.attachments.forEach((attachment, index) => {
console.log(` ${index + 1}. ${attachment.name || attachment.url}`);
});
}
} catch (error) {
console.error('Error parsing message:', error);
}
}
});Group Chat Integration
const groupChatClient = createSSEClient({
url: 'https://chatapi.onewise.app/bot-listen',
accessToken: 'your-access-token',
roomId: 'team-developers',
onMessage: (data) => {
try {
const messageData = JSON.parse(data);
// Handle different message types
switch (messageData.type) {
case 'message':
console.log(`👤 ${messageData.sender}: ${messageData.text}`);
// Display attachments if any
if (messageData.attachments.length > 0) {
messageData.attachments.forEach(attachment => {
console.log(`📎 ${attachment.type}: ${attachment.name}`);
});
}
break;
case 'user_joined':
console.log(`✅ ${messageData.user} joined the group`);
break;
case 'user_left':
console.log(`❌ ${messageData.user} left the group`);
break;
}
} catch (error) {
console.error('Failed to parse group message:', error);
}
}
});Private Chat Handling
const privateChatClient = createSSEClient({
url: 'https://chatapi.onewise.app/bot-listen',
accessToken: 'private-token',
roomId: 'user_123_456', // Private room between user 123 and 456
onMessage: (rawData) => {
try {
const message = JSON.parse(rawData);
// Private message structure: { text: "Hello!", attachments: [], sender: "user_123", timestamp: "2024-01-01T00:00:00Z" }
const { text, attachments, sender, timestamp } = message;
console.log(`💬 [${new Date(timestamp).toLocaleTimeString()}] ${sender}:`);
console.log(` ${text}`);
// Handle media attachments
if (attachments && attachments.length > 0) {
console.log(`📎 Attachments:`);
attachments.forEach((file, index) => {
const fileType = file.type || 'unknown';
const fileName = file.name || `attachment_${index + 1}`;
const fileSize = file.size ? ` (${(file.size / 1024).toFixed(1)}KB)` : '';
console.log(` ${index + 1}. [${fileType.toUpperCase()}] ${fileName}${fileSize}`);
});
}
} catch (parseError) {
// If not JSON, might be plain text message
console.log(`📝 Raw message: ${rawData}`);
}
},
onError: (error) => {
console.error('❌ Private chat connection error:', error);
}
});Complete Chat Message Handler
const createSSEClient = require('sse-client-auth-onewise');
// Utility function to format chat messages
function formatChatMessage(messageData) {
const { text, attachments = [], sender, timestamp, messageId } = messageData;
// Format timestamp
const time = timestamp ? new Date(timestamp).toLocaleTimeString() : 'now';
// Main message
console.log(`💬 [${time}] ${sender || 'Unknown'}: ${text || '(no text)'}`);
// Handle different attachment types
if (attachments.length > 0) {
console.log(`📎 ${attachments.length} attachment(s):`);
attachments.forEach((attachment, index) => {
const { type, name, url, size } = attachment;
const sizeText = size ? ` (${formatFileSize(size)})` : '';
switch (type) {
case 'image':
console.log(` ${index + 1}. 🖼️ Image: ${name}${sizeText}`);
break;
case 'video':
console.log(` ${index + 1}. 🎥 Video: ${name}${sizeText}`);
break;
case 'audio':
console.log(` ${index + 1}. 🎵 Audio: ${name}${sizeText}`);
break;
case 'document':
console.log(` ${index + 1}. 📄 Document: ${name}${sizeText}`);
break;
default:
console.log(` ${index + 1}. 📎 File: ${name || url}${sizeText}`);
}
});
}
}
// Helper function to format file sizes
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Create the SSE client
const chatClient = createSSEClient({
url: 'https://chatapi.onewise.app/bot-listen',
accessToken: 'your_access_token_here',
roomId: 'chat_room_id', // Optional for group chat
onMessage: (rawMessage) => {
try {
// Parse the stringified message
const messageData = JSON.parse(rawMessage);
// Format and display the message
formatChatMessage(messageData);
} catch (error) {
console.error('❌ Error parsing message:', error);
console.log('📝 Raw message:', rawMessage);
}
},
onError: (error) => {
console.error('❌ SSE Connection Error:', error);
},
onOpen: () => {
console.log('✅ Connected to chat stream');
}
});📨 Message Format
The SSE server sends messages in JSON format with the following structure:
// Basic message structure
{
"text": "Hello everyone! 👋",
"attachments": [],
"sender": "user_123",
"timestamp": "2024-01-01T12:00:00Z",
"messageId": "msg_456",
"type": "message"
}
// Message with attachments
{
"text": "Check out these files!",
"attachments": [
{
"type": "image",
"name": "screenshot.png",
"url": "https://example.com/files/screenshot.png",
"size": 245760
},
{
"type": "document",
"name": "report.pdf",
"url": "https://example.com/files/report.pdf",
"size": 1048576
}
],
"sender": "user_789",
"timestamp": "2024-01-01T12:05:00Z",
"messageId": "msg_789"
}
// System message (user joined/left)
{
"text": "User John joined the conversation",
"attachments": [],
"type": "system",
"timestamp": "2024-01-01T12:10:00Z"
}Attachment Types
| Type | Description | Example Extensions |
|------|-------------|-------------------|
| image | Image files | .jpg, .png, .gif, .webp |
| video | Video files | .mp4, .avi, .mov, .webm |
| audio | Audio files | .mp3, .wav, .ogg, .m4a |
| document | Document files | .pdf, .doc, .txt, .xlsx |
| other | Other file types | Any other extension |
🔗 Connection URL Format
The client automatically appends authentication parameters to your URL:
Original URL: https://example.com/events
Final URL: https://example.com/events?accessToken=your_token&roomId=room_idconst sseClient = createSSEClient({
url: 'https://chatapi.onewise.app/bot-listen',
accessToken: 'token',
onMessage: (data) => {
console.log('Message:', data);
},
onError: (error) => {
console.error('Connection error:', error);
// Custom retry logic
setTimeout(() => {
console.log('Attempting to reconnect...');
// Create new client instance
}, 5000);
}
});📋 Requirements
- Node.js >= 12.0.0
- Active internet connection
- SSE-compatible server endpoint
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🐛 Issues
If you encounter any issues or have questions, please file an issue on the GitHub repository.
📝 Changelog
v1.0.0
- Initial release
- Basic SSE client functionality
- Authentication via query parameters
- Error handling support
Made with ❤️ for the Node.js community
