Channel Basics

A channel is a communication pathway for passing data between devices with PubNub.

Channels are hosted on PubNub. You interact with channels using PubNub SDKs (Software Development Kit, SDK) or the REST API (Representational State Transfer, REST).

Pub/sub enables efficient, asynchronous message processing. Your app can deliver real-time updates while components work independently. For example, in chat, messaging, notifications, and analytics can each communicate through channels to keep the design modular and scalable.

We are fast

Devices listening on a channel typically receive messages in about 30 ms, enabling swift global communication.

Channel creation

You don’t create channels in advance. PubNub creates a channel the first time you publish to it.

Channel entity

PubNub SDKs provide local Channel entities to help you work with channels. These objects hide channel-management details and support clean patterns, such as decoupling app components for maintainability.

For more information, refer to Entities.

Channel limits

There’s no limit on the number of channels or users per channel. A device can listen to thousands of channels over a single connection, which supports large-scale communication.

Channel types

Channels represent places where messages are sent and received. Use direct channels for one-to-one private messaging and group channels for many-to-many conversations. Broadcast and unicast channels fit one‑to‑many and many‑to‑one use cases.

Here are some useful channel configurations:

Direct channels for one-to-one in-app messaging between two users. You can make these channels private to keep the messages secure between the users.

const PubNub = require('pubnub');

// Initialize the PubNub client with your publish and subscribe keys
const pubnub = new PubNub({
publishKey: 'yourPublishKey',
subscribeKey: 'yourSubscribeKey',
userId: 'user1-unique-id', // Use unique user IDs for authentication
authKey: 'user1AuthKey', // Use an authentication key for security
ssl: true // Enable SSL for secure communication
});

// Define the direct channel for one-to-one messaging between two specific users
const directChannel = 'direct.user1.user2'; // Example channel name

// Subscribe to the direct channel
const channel = pubnub.channel(directChannel);
const subscription = channel.subscription();

// Add event listeners for messages and presence
subscription.onMessage = (messageEvent) => {
console.log('Received message:', messageEvent.message);
};

subscription.onPresence = (presenceEvent) => {
console.log('Presence event:', presenceEvent);
};

// Subscribe to the channel
subscription.subscribe();

// Function to send a message to the direct channel
async function sendMessage(message) {
return pubnub.publish({
channel: directChannel,
message: { text: message },
meta: { sender: 'user1' }, // Add meta to store sender info
storeInHistory: true, // Store messages in history
customMessageType: "text-message", // Label the message type
});
}
// Example: sending a message
sendMessage('Hello, user2!')
.then((result) => {
console.log('Message sent successfully');
})
.catch((error) => {
console.error('Error sending message:', error);
}) ;
show all 48 lines

Group channels serve as a collective category for many-to-many in-app messaging among multiple users, forming a community communication system, such as a chat room for friends or family.

const PubNub = require('pubnub');

// Initialize the PubNub client with your publish and subscribe keys
const pubnub = new PubNub({
publishKey: 'yourPublishKey',
subscribeKey: 'yourSubscribeKey',
userId: 'user1-unique-id', // Use unique user IDs for authentication
authKey: 'user1AuthKey', // Use an authentication key for security if necessary
ssl: true // Enable SSL for secure communication
});

// Define the group channel for in-app messaging
const groupChannel = 'group.family'; // Example channel name for a family group

// Subscribe to the group channel
const channel = pubnub.channel(groupChannel);
const subscription = channel.subscription();

// Add event listeners for messages and presence
subscription.onMessage = (messageEvent) => {
console.log('Received message:', messageEvent.message);
};

subscription.onPresence = (presenceEvent) => {
console.log('Presence event:', presenceEvent);
};

// Subscribe to the channel
subscription.subscribe();

// Function to send a message to the group channel
async function sendMessage(message) {
try {
await pubnub.publish({
channel: groupChannel,
message: { text: message },
meta: { sender: 'user1' }, // Add meta to store sender info
storeInHistory: true, // Store messages in history
customMessageType: "text-message", // Label the message type
});
console.log('Message sent successfully');
} catch (error) {
console.error('Error sending message:', error);
}
}

// Example: sending a message
sendMessage('Hello, family group!');

// Optional: manage access (only required if making the group private)
function manageAccess() {
pubnub.grant({
channels: [groupChannel],
authKeys: ['user1AuthKey', 'user2AuthKey', 'user3AuthKey'], // Auth keys for allowed users
read: true,
write: true,
ttl: 60 // Time-to-live for the grant in minutes
}, (status) => {
if (status.error) {
console.error('Error managing access:', status);
} else {
console.log('Access managed successfully');
}
});
}

// Call this function if you want to restrict the channel to certain users
manageAccess();
show all 68 lines

Broadcast channels for announcements, polls, and other situations in which you want to broadcast messages in a one-to-many arrangement.

const PubNub = require('pubnub');

// Initialize the PubNub client with your publish and subscribe keys
const pubnub = new PubNub({
publishKey: 'yourPublishKey',
subscribeKey: 'yourSubscribeKey',
userId: 'broadcaster-unique-id', // Use a unique ID for the broadcaster
ssl: true // Enable SSL for secure communication
});

// Define the broadcast channel for one-to-many communication
const broadcastChannel = 'broadcast.announcements'; // Example channel for announcements

// Subscribe to the broadcast channel
const channel = pubnub.channel(broadcastChannel);
const subscription = channel.subscription();

// Add an event listener for messages
subscription.onMessage = (messageEvent) => {
console.log('Received broadcast message:', messageEvent.message);
};

// Subscribe to the channel
subscription.subscribe();

// Function to send a broadcast message to the broadcast channel
async function sendBroadcastMessage(message) {
try {
await pubnub.publish({
channel: broadcastChannel,
message: { text: message },
storeInHistory: false, // Typically, broadcasts do not need to be stored
customMessageType: "broadcast", // Label the message as a broadcast
});
console.log('Broadcast message sent successfully');
} catch (error) {
console.error('Error sending broadcast message:', error);
}
}

// Example: sending a broadcast message
sendBroadcastMessage('Attention all users, system maintenance at midnight!');

// Function to configure broadcast settings
function configureBroadcastChannel() {
// You might implement additional logic here to ensure only certain clients can publish to the channel
// This could involve permissions management if implemented server-side
}

// Optionally call this function to manage and configure channel access and settings
configureBroadcastChannel();
show all 51 lines

Unicast channels for poll responses, sensor inputs, location data, and other situations in which you want to aggregate messages in a many-to-one arrangement.

const PubNub = require('pubnub');

// Initialize the PubNub client with your publish and subscribe keys
const pubnub = new PubNub({
publishKey: 'yourPublishKey',
subscribeKey: 'yourSubscribeKey',
userId: 'listener-unique-id', // Unique ID for the device/server listening for inputs
ssl: true // Enable SSL for secure communication
});

// Define the unicast channel for aggregating messages
const unicastChannel = 'unicast.dataCollector'; // Example channel for aggregating data

// Subscribe to the unicast channel
const channel = pubnub.channel(unicastChannel);
const subscription = channel.subscription();

// Add an event listener for messages
subscription.onMessage = (messageEvent) => {
console.log('Received message:', messageEvent.message);
// Process the incoming data
processIncomingData(messageEvent.message);
};

// Subscribe to the channel
subscription.subscribe();

// The function for processing incoming data
function processIncomingData(data) {
// Implement your data processing logic here
console.log('Processing data:', data);
}

// Function for sending data to the unicast channel from different devices
async function sendData(deviceId, data) {
try {
await pubnub.publish({
channel: unicastChannel,
message: { deviceId: deviceId, data: data },
storeInHistory: true, // Optional: store data for historical analysis
customMessageType: "sensor-data", // Label the message type
});
console.log('Data sent successfully from device:', deviceId);
} catch (error) {
console.error('Error sending data from device:', deviceId, error);
}
}

// Example: devices sending data to the unicast channel
sendData('device1', { temperature: 22.5, humidity: 45 });
sendData('device2', { location: { lat: 37.7749, lon: -122.4194 } });

// Optionally, function for configuring access if needed
function configureUnicastChannel() {
// You can manage which users or devices are allowed to publish to the channel
// This can involve permissions management if implemented server-side
}

// Optionally call this function to set up access and permissions
configureUnicastChannel();
show all 60 lines

Channel groups allow you to bundle thousands of channels into a group that can be identified by name. When you subscribe to a channel group, you receive data from all the channels the channel group contains.

Channel names

A channel name can be any alphanumeric string up to 92 UTF‑8 characters. Channel names are unique per PubNub key set. You can reuse the same name in a different key set, even within the same account. A key set is the namespace for your channels.

Invalid characters

, : * / \ and Unicode Null, whitespace, and non‑printable ASCII characters.

Valid characters

_ - = @ . ! $ # % & ^ ;

A period (.) is valid. It is also a special character for wildcard features. Use it strategically to enable wildcard channel subscribe and Function wildcard channel binding.

Channel name validator

Check if your channel name is valid using the channel name validator.

Naming conventions

When it comes to naming your channels, we recommend that you provide a prefix that identifies the purpose of the channel or the types of messages that will be sent over those types of channels.

Following that prefix with a . character further enhances the usefulness of the channel name concerning the wildcard features with several PubNub features, like wildcard subscribe, wildcard channel function binding, and advanced Presence configuration.

For further details on channel naming recommendations, refer to Channel Naming Conventions.

Securing channels

Secure channels by controlling access with PubNub’s Access Manager.

While you are learning PubNub, you can keep Access Manager disabled so any client can send and receive on any channel. For production, enable access control to protect your channels.

For app‑wide protection, see Access Control in the Security section.

Last updated on