This blog post was written under the Pusher Guest Writer program.

Applications can generate a lot of events when they’re running. However, most of the time, the only way to know what’s going on is by looking at the logs or running queries against the database. It would be nice to let the users see what is going on in an easy way, so why not build an activity feed to see in real-time, every change made to the models of the application?

In this tutorial we are going to build a simple Node.js REST API with Express and Mongoose to work with generic measurements, let’s say for example, temperatures. Every time a database record is modified (created/updated/deleted), it will trigger an event to a channel in real-time using Pusher. In the front-end, those events will be shown in an activity feed made with React.

This is how the final application will look like:

Final app

This tutorial assumes prior knowledge of Node.js and React. We will integrate Pusher into a Node.js API, create React components and hook them up with Pusher. However, since Pusher is so easy to use together with Node.js and React, you might feel that in this tutorial we will spend most of our time setting things up in the backend and creating the React components.

You’ll need to have access to a MongoDB database. If you’re new to MongoDB, you might find this documentation on how to install it handy.

The source code of the final version of the application is available on Github.

Application Structure

The project has the following structure:

|— models
| |— measure.js
|— public
| |— css
| |— images
| |— js
| | |— app.js
| | |— event.js
| | |— events.js
| | |— header.js
|— routes
| |— api.js
| |— index.js
|— views
| |— index.ejs
|- package.json
|- server.js
  • The model directory contains the Mongoose schema to interact with the database.
  • The public directory contains the CSS and images files as well as the Javascript (React) files that will be used on the main web page of the app.
  • The routes directory contains the server’s API endpoints and the route to server the main page of the app.
  • The view directory contains the EJS template for the main page of the app.
  • In the root directory, we can find the package.json file with the project’s dependencies and the file for the Express server.

Setting up Pusher

Create a free account at https://pusher.com/signup.

When you first log in, you’ll be asked to enter some configuration options:

Create Pusher app

Enter a name, choose React as your front-end tech, and Node.js as your back-end tech. This will give you some sample code to get you started.

Pusher Getting Started tab

This won’t lock you into a specific set of technologies, you can always change them. With Pusher, you can use any combination of libraries.

Then go to the App Keys tab to copy your App ID, Key, and Secret credentials, we’ll need them later.

Setting up the application

First, add a default package.json configuration file with:

npm init -y

For running the server, we’ll need Express, React, Pusher, and other dependencies, let’s add them with:

npm install --save express ejs body-parser path pusher mongoose

Here are the dependencies section on the package.json file in case a future version of a dependency breaks the code:

{
  ...
  "dependencies": {
    "body-parser": "^1.15.2",
    "ejs": "^2.5.2",
    "express": "^4.14.0",
    "mongoose": "^4.6.4",
    "path": "^0.12.7",
    "pusher": "^1.5.0",
  }
}

The Node.js Back-end

The back-end is a standard Express app with Mongoose to interact with the database. In the server.js file, you can find the configuration for Express:

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(path.join(__dirname, 'public')));

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

The routes exposed to the server are organized in two different files:

app.use('/', index);
app.use('/api', api);

Then, the app will connect to the database and start the web server on success:

mongoose.connect('mongodb://localhost/temperatures');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'Connection Error:'));
db.once('open', function () {
  app.listen(3000, function () {
    console.log('Node server running on port 3000');
  });
});

However, the interesting part is in the file routes/api.js. First, the Pusher object is created passing the configuration object with the App ID, the key, and the secret for the Pusher app:

var pusher = new Pusher({
  appId      : process.env.PUSHER_APP_ID,
  key        : process.env.PUSHER_APP_KEY,
  secret     : process.env.PUSHER_APP_SECRET,
  encrypted  : true,
});

Pusher can be used to publish any events that happen in our application. These events have a channel, which allows events to relate to a particular topic, an event-name used to identify the type of the event, and a payload, which you can attach any additional information to the message.

We are going to publish an event to a Pusher channel when a database record is created/updated/deleted with that record as attachment so we can show it in an activity feed.

Here’s the definition of our API’s REST endpoints. Notice how the event is triggered using pusher.trigger after the database operation is performed successfully:

/* CREATE */
router.post('/new', function (req, res) {
  Measure.create({
    measure: req.body.measure,
    unit: req.body.unit,
    insertedAt: Date.now(),
  }, function (err, measure) {
    if (err) {
      ...
    } else {
      pusher.trigger(
        channel,
        'created', 
        {
          name: 'created',
          id: measure._id,
          date: measure.insertedAt,
          measure: measure.measure,
          unit: measure.unit,
        }
      );

      res.status(200).json(measure);
    }
  });
});

router.route('/:id')
  /* UPDATE */
  .put((req, res) => {
    Measure.findById(req.params.id, function (err, measure) {
      if (err) {
        ...
      } else if (measure) {
        measure.updatedAt = Date.now();
        measure.measure = req.body.measure;
        measure.unit = req.body.unit;

        measure.save(function () {
          pusher.trigger(
            channel,
            'updated', 
            {
              name: 'updated',
              id: measure._id,
              date: measure.updatedAt,
              measure: measure.measure,
              unit: measure.unit,
            }
          );

          res.status(200).json(measure);
        });


     } else {
        ...
      }
    });
  })

  /* DELETE */
  .delete((req, res) => {
    Measure.findById(req.params.id, function (err, measure) {
      if (err) { 
        ...
      } else if (measure) {
        measure.remove(function () {
          pusher.trigger(
            channel,
            'deleted', 
            {
              name: 'deleted',
              id: measure._id,
              date: measure.updatedAt ? measure.updatedAt : measure.insertedAt,
              measure: measure.measure,
              unit: measure.unit,
            }
          );

          res.status(200).json(measure);
        });
     } else {
        ...
      }
    });
  });

Measure is the Mongoose schema used to access the database. You can find its definition in the models/measure.js file:

var measureSchema = new Schema({  
  measure:     { type: Number },
  insertedAt:  { type: Date },
  updatedAt:   { type: Date },
  unit:        { type: String },
});

This way, we’ll be listening to these events to update the state of the client in the front-end.

React + Pusher

React thinks of the UI as a set of components, where you simply update a component’s state, and then React renders a new UI based on this new state updating the DOM for you in the most efficient way.

The app’s UI will be organized into three components, a header (Header), a container for events (Events), and a component for each event (Event):

React Components

The template for the index page is pretty simple. It just contains references to the CSS files, a div element where the UI will be rendered, the Pusher app key (passed from the server), and references to all the Javascript files the application uses:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Realtime Activity Feed with Pusher + React</title>
  <link rel="stylesheet" href="/css/all-the-things.css">
  <link rel="stylesheet" href="/css/style.css">
</head>

<body class="blue-gradient-background">

  <div id="app"></div>

  <!-- React -->
  <script src="https://unpkg.com/react@15.3.2/dist/react-with-addons.js"></script>
  <script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

  <!-- Libs -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
  <script src="https://js.pusher.com/3.2/pusher.min.js"></script>

  <!-- Pusher Config -->
  <script>
    var PUSHER_APP_KEY = '<%= pusher_app_key %>';
  </script>

  <!-- App/Components -->
  <script type="text/babel" src="/js/header.js"></script>
  <script type="text/babel" src="/js/event.js"></script>
  <script type="text/babel" src="/js/events.js"></script>
  <script type="text/babel" src="/js/app.js"></script>

</body>
</html>

The application will be rendered in the div element with the ID app. The file public/js/app.js is the starting point for our React app:

var App = React.createClass({
  ...
});

ReactDOM.render(<App />, document.getElementById("app"));

Inside the App class, first, we define our state as an array of events:

var App = React.createClass({

  getInitialState: function() {
    return { events: [] };
  },

  ...

});

Then, we use the componentWillMount method, which is invoked once immediately before the initial rendering occurs, to set up Pusher:

var App = React.createClass({

  ...

  componentWillMount: function() {
    this.pusher = new Pusher(PUSHER_APP_KEY, {
      encrypted: true,
    });
    this.channel = this.pusher.subscribe('events_to_be_shown');
  }, 

  ...
});

...

We subscribe to the channel’s events in the componentDidMount method and unsubscribe from all of them and from the channel in the componentWillUnmount method:

var App = React.createClass({

  ... 

  componentDidMount() {
    this.channel.bind('created', this.updateEvents);
    this.channel.bind('updated', this.updateEvents);
    this.channel.bind('deleted', this.updateEvents);
  }

  componentWillUnmount() {
    this.channel.unbind();

    this.pusher.unsubscribe(this.channel);
  } 

  ...
});

...

The updateEvents function updates the state of the component so the UI can be re-render. Notice how the new event is prepended to the existing array of events. Since React works best with immutable objects, we create a copy of that array to then update this copy:


var App = React.createClass({ ... updateEvents: function(data) { var newArray = this.state.events.slice(0); newArray.unshift(data); this.setState({ events: newArray, }); }, ... }); ...

Finally, the render method shows the top-level components of our app, Header and Events:

var App = React.createClass({

  ...

  render() {
    return (
      <div>
        <Header  />
        <Events events={this.state.events} />
      </div>
    );
  }

  ...
}

...

public/javascript/header.js is a simple component without state or properties that only renders the HTML for the page’s header.

The Events component (public/javascript/events.js) takes the array of events to create an array of Event components:

var Events = React.createClass({
  render: function() {
    var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;

    var eventsLength = this.props.events.length;
    var eventsMapped = this.props.events.map(function (evt, index) {
      const key = eventsLength - index;
      return <Event event={evt} key={key} />
    });

    return <section className={'blue-gradient-background intro-splash splash'}>
             <div className={'container center-all-container'}>
               <h1 className={'white light splash-title'}>
                 Realtime Activity Feed with Pusher + React
               </h1>
               <ReactCSSTransitionGroup component="ul" className="evts" transitionName="evt-transition" transitionEnterTimeout={500} transitionLeaveTimeout={500}>
                 {eventsMapped}
               </ReactCSSTransitionGroup>
             </div>
           </section>;
    }
});

There are two important things in this code.

First, React requires every message component in a collection to have a unique identifier defined by the key property. This help it to know when elements are added or removed. As new elements are prepended instead of appended, we can’t give the first element the index 0 as key since this will only work the first time an element is added (for the next added elements, there will be an element with key 0 already). Therefore, keys are assigned this way:

var key = eventsLength - index;

The second thing is that the insertion of a new event is done with the ReactCSSTransitionGroup add-on component, which wraps the elements you want to animate. By default, it renders a span to wrap them, but since we’re going to work with li elements, we specify the wrapper tag ul with the component property. className becomes a property of the rendered component, as any other property that doesn’t belong to ReactCSSTransitionGroup.

transitionName is the prefix used to identify the CSS classes to perform the animation. You can find them in the file public/css/style.css:

.evt-transition-enter {
    opacity: 0.01;
}

.evt-transition-enter.evt-transition-enter-active {
    opacity: 1;
    transition: opacity 500ms ease-in;
}

.evt-transition-leave {
    opacity: 1;
}

.evt-transition-leave.evt-transition-leave-active {
    opacity: 0.01;
    transition: opacity 500ms ease-in;
}

Finally, the Event component (public/js/event.js), using Moment.js to format the date, renders the event in the following way:

var Event = React.createClass({
render: function() {
var name = this.props.event.name;
var id = this.props.event.id;
var date = moment(this.props.event.date).fromNow();
var measure = this.props.event.measure;
var unit = this.props.event.unit;

  return (
    <li className={'evt'}>
      <div className={'evt-name'}>{name}:</div>
      <div className={'evt-id'}>{id}</div>
      <div className={'evt-date'}>{date}</div>
      <div className={'evt-measure'}>{measure}&deg;{unit}</div>
    </li>
  );
}

});

To run the server, execute the server.js file using the following command:

PUSHER_APP_ID=<YOUR PUSHER APP ID> PUSHER_APP_KEY=<YOUR PUSHER APP KEY> PUSHER_APP_SECRET=<YOUR PUSHER APP SECRET> node server.js

To test the whole app, you can use something to call the API endpoints with a JSON payload, like curl or Postman:

Postman

Or if you only want to test the front-end part with Pusher, you can use the Pusher Debug Console on your dashboard:

Pusher Console

Conclusion

In this tutorial, we saw how to integrate Pusher into a Node.js back-end and a React front-end. As you can see, it is trivial and easy to add Pusher to your app and start adding new features. You can start on the forever free plan that includes 100 max connections, unlimited channels, 200k daily messages, and SSL protection. Signup now!

Remember that if you get stuck, you can find the final version of this code on Github or contact us with your questions.

Further reading