DEV Community

Cover image for Pusher: Real-Time Functionality
josesrodriguez610
josesrodriguez610

Posted on

Pusher: Real-Time Functionality

Every time I’m building a chat I always think about working with socket.io but this time I wanted to find something different and that’s when I came across Pusher.
Pusher is a hosted service that makes it easy for us developers to add real-time and functionality to your application. They even give you instructions on how to use the code in the website. I’ve seen a lot
Tutorials of people using it with mongoose but it can be done with Sequelize as well. I’ve been working in an application that uses Sequelize and React and I’m going to show you briefly how it works. First let’s go to Pusher and start an account.

When you go to pusher first you are going to sign for a free account.

Alt Text

Once you create an account lets create a Channel

Alt Text

and You will be asked to pick a name for your application and then what are you using for your frontend and backend.
This way Pusher will give you a couple of snippets to help you set it up in your application.

Alt Text

Here you have instructions on how to set it up for the backend and frontend.

Backend
Alt Text

Frontend
Alt Text

Now let’s go to our code.

First we need to install pusher

npm install pusher
Enter fullscreen mode Exit fullscreen mode

I’m working with a database so I’m importing my model called Message and I’m using express router to create a specific route for my messages. I’m using dotenv to hide my keys information.
now let’s bring pusher to our backend by importing it and then
look at node.js there is a snippet on how to do it.

require('dotenv').config();
const { Router } = require('express');
const { Message } = require('../db/index');
const Pusher = require('pusher');

const messageRouter = Router();


const pusher = new Pusher({
  appId: process.env.PUSHER_ID,
  key: process.env.PUSHER_KEY,
  secret: process.env.PUSHER_SECRET,
  cluster: process.env.CLUSTER,
  useTLS: true
});


module.exports = { messageRouter };
Enter fullscreen mode Exit fullscreen mode

First you are going to have a post request that will save the message information sent to the database and in there we are going to listen to any changes and send them back to show data right away!

messageRouter.post('/', (req, res) => {
  const {
    id_league, words, id_user, username
  } = req.body;

  Message.create({
    id_league, id_user, words, username
  })
    .then((response) =>  res.send('message created’))
    .catch((error) => console.warn(error));
});
Enter fullscreen mode Exit fullscreen mode

So I’ve created a route to create a message that takes a body with a league id, user id, words which is the message and the username.
I’m using Sequelize so I’m using create to save it to the database and then once it it create my response is just letting me know that the message has been created.

Now right after the response we are going to add the listener.

If you look at the Pusher code snippet. When you use the trigger you need to add a channel which it will be messages, and an event which we called inserted.

messageRouter.post('/', (req, res) => {
  const {
    id_league, words, id_user, username
  } = req.body;

  Message.create({
    id_league, id_user, words, username
  })
    .then((response) => {
      pusher.trigger('messages', 'inserted', {
        id_league: response.id_league,
        id_user: response.id_user,
        words: response.words,
        username: response.username,
        createdAt: response.createdAt
      });
      res.send('message sent');
    })
    .catch((error) => console.warn(error));
Enter fullscreen mode Exit fullscreen mode

Now let’s go to the front-end.

First we are going to install pusher-js

npm install pusher.js
Enter fullscreen mode Exit fullscreen mode

Then we are going to import it and use useState and useEffect from react.
useEffect will be saving our messages in an array.
Then you can look at the code snippet provided by Pusher and add this to the use effect. There you are going to add your pusher key.

import React, { useState, useEffect } from 'react';
import Pusher from 'pusher-js';

function MessageBoard() {

useEffect(() => {
    const pusher = new Pusher(process.env.PUSHER_KEY, {
      cluster: 'us2'
    });

    const channel = pusher.subscribe('messages');
    channel.bind('inserted', (newMessage) => {
      setMessages([...messages, newMessage]);
    });

    return () => {
      channel.unbind_all();
      channel.unsubscribe();
    };
  }, [messages]);
Enter fullscreen mode Exit fullscreen mode

Now you are listening to the messages channel and you are binding it to the event which is inserted. setState then will add it to our array and the useEffect.
Then I’m canceling the listener for better performance.

This is a quick way to show how Pusher works in your application. I encourage you to go and check out the documents. It is very easy to set up and I’ll be using it again in the future.

Top comments (0)