PusherJS is a JavaScript library that allows us to easily implement real-time communication in our web applications using WebSockets.
With PusherJS, we can add functionalities like real-time notifications, live updates, and chats to our applications, significantly enhancing the user experience.
PusherJS stands out for its following features:
- Simplicity: It offers an easy-to-use API for handling real-time events.
- Scalability: It allows us to scale our applications without additional complications.
- Reliability: It ensures the secure and efficient delivery of real-time messages.
- Compatibility: Support for various languages and platforms, making integration with our tech stack easier.
It is very interesting for IoT applications. Additionally, it has a very generous free tier, allowing up to 200,000 messages daily. Enough for all your projects combined.
Installing PusherJS
To start using PusherJS in our applications, we first need to sign up at Pusher and obtain our API credentials. Then, we can install the library via npm or include it directly in our HTML.
Installation via npm
If we are using a package manager like npm, we can install PusherJS with the following command:
npm install pusher-js
Inclusion in HTML
We can also include PusherJS directly in our HTML using a <script>
tag:
<script src="https://js.pusher.com/7.0/pusher.min.js"></script>
How to Use PusherJS
Initial Setup
First, we need to configure Pusher with our API credentials. Here is a basic configuration example:
import Pusher from 'pusher-js';
const pusher = new Pusher('YOUR_APP_KEY', {
cluster: 'YOUR_APP_CLUSTER'
});
Subscribing to Channels and Listening for Events
We can subscribe to a channel and listen for events like this:
const channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
console.log('Received event:', data);
});
In this example, we subscribe to the my-channel
channel and listen for the my-event
event. When the event is triggered, the callback function executes and logs the event information to the console.
Sending Events from the Server
To send events from our server, we can use the Pusher libraries for different languages. Below is an example in Node.js:
const Pusher = require('pusher');
const pusher = new Pusher({
appId: 'YOUR_APP_ID',
key: 'YOUR_APP_KEY',
secret: 'YOUR_APP_SECRET',
cluster: 'YOUR_APP_CLUSTER'
});
pusher.trigger('my-channel', 'my-event', {
message: 'Hello, world!'
});
In this example, we configure Pusher with our credentials and send a my-event
event to the my-channel
channel with a message.
Complete Example
Let’s look at a more complete example of how to implement real-time notifications using PusherJS. We will assume we are building a chat application.
Frontend (HTML + JavaScript)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chat App</title>
<script src="https://js.pusher.com/7.0/pusher.min.js"></script>
</head>
<body>
<div id="messages"></div>
<input type="text" id="messageInput" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
<script>
const pusher = new Pusher('YOUR_APP_KEY', {
cluster: 'YOUR_APP_CLUSTER'
});
const channel = pusher.subscribe('chat-channel');
channel.bind('new-message', function(data) {
const messagesDiv = document.getElementById('messages');
const newMessage = document.createElement('div');
newMessage.textContent = data.message;
messagesDiv.appendChild(newMessage);
});
function sendMessage() {
const message = document.getElementById('messageInput').value;
fetch('/send-message', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message })
});
}
</script>
</body>
</html>
Backend (Node.js)
const express = require('express');
const bodyParser = require('body-parser');
const Pusher = require('pusher');
const app = express();
const pusher = new Pusher({
appId: 'YOUR_APP_ID',
key: 'YOUR_APP_KEY',
secret: 'YOUR_APP_SECRET',
cluster: 'YOUR_APP_CLUSTER'
});
app.use(bodyParser.json());
app.post('/send-message', (req, res) => {
const message = req.body.message;
pusher.trigger('chat-channel', 'new-message', { message });
res.sendStatus(200);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example,
- We have a frontend that sends messages to the server via a POST request.
- The server, in turn, uses Pusher to send the message to the
chat-channel
- This is received by all clients subscribed to the channel.