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

sse-client-auth-onewise

v1.0.6

Published

A simple SSE client with accessToken authentication

Readme

sse-client-auth-onewise

npm version License: MIT

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_id
const 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.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. 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