Build scalable realtime features


Programmatic push notifications



Read the docs to learn how to use our products


Explore our tutorials to build apps with Pusher products


Reach out to our support team for help and advice

Sign in
Sign up

Add live comments in Gatsby

  • Christian Nwamba

June 12th, 2018
You will need Node and npm or Yarn installed on your machine. A basic understanding of JavaScript will be helpful.

According to Wikipedia, a static web page (sometimes called a flat page/stationary page) is a web page that is delivered to the user exactly as stored, in contrast to dynamic web pages which are generated by a web application

Gatsby is a modern static site generator that allows you to build static web pages using React and GraphQl. Getting started with Gatsby is pretty easy and its installation is an npm install or yarn install away.

Today we’ll be adding a realtime comment section to the sports blog we’ll be building. We’ll call our blog the “Football transfer buzz with Gordon Mc-gossip”. Our application will contain a post and allow users to leave comments and everyone gets to see it in realtime.


  1. Kindly ensure you have Node, Npm or Yarn installed on your machine before moving past this section. This will be needed for running and managing the dependencies needed by our application.
  2. Also, no knowledge of React is required, but a basic understanding of JavaScript may be helpful.
  3. Pusher: this is a framework that allows you to build realtime applications with its easy to use pub/sub messaging API.
  4. Gatsby: this is a static site generator. ( minimum version "gatsby": "^1.9.247")

Install Gatsby

Installing Gatsby is pretty easy once you have Node installed on your machine. Simply run:

    # for npm users
    npm i -g gatsby-cli
    # for yarn users
    yarn global add gatsby-cli

This Gatsby CLI comes with a few helpful commands that can help you build and test your apps locally.

Create your app

To create our project, simply run:

    # new gatsby project
    gatsby new gatsby-site-pusher

This will create our new project Transfer-Buzz and install its dependencies. If you cd into your new project directory, it will look like this.

Most of the work we’ll be doing would be in the src/ directory. The components we’ll create would go into the src/components directory and pages would go into the src/pages directory.

Install dependency:

    # for npm users
    npm i --save pusher-js
    # for yarn users
    yarn add pusher-js

Get our Pusher credentials

If you don't have a Pusher account already, kindly create one here. Once you have an account, simply head down to your dashboard and create an app. Once that is done, click on App Keys and note your credentials. We'll be needing them in a bit.

Creating our app components

The first component we’ll create is our CommentList component. This will be responsible for listing the comments left by users.

    // src/components/comment-list.js

    import React from 'react'

    export default ({comments}) => {
      comments =, i) => (
        <div key={i} style={{
          padding: '5px',
          border: '1px solid grey'
      return (
          <strong>Comments: </strong>{comments}

This simply takes an array of comments with attributes {author, message} and returns a CommentList component.

Next, is the Comment component, which will have a form for accepting new comments and list comments below.

    // src/components/comment.js
    import React, { Component } from 'react'
    import CommentList from './comment-list'
    import Pusher from 'pusher-js'

    * initialize pusher with your credentials.
    * Get 'key' from pusher dashboard
    const pusher = new Pusher('key', {
      cluster: 'eu',
      encrypted: true

    // subscribe your pusher instance to the channel 'sport-buzz-news'
    const channel = pusher.subscribe('sport-buzz-news')

    /* global fetch */
    export default class Comment extends Component {
      constructor (props) {
        this.state = {
          comments: [],
          author: '',
          message: ''

    * This will load components from the server on app startup,
    * and also subscribe our app to listen for updates
      async componentDidMount () {
        const comments = await fetch('http://localhost:8080/comments').then(res => res.json())
        this.setState({comments: [...comments, ...this.state.comments]})

      componentWillUnmount () {

      * add new comments to the top of the list
      * once there's an update
      receiveUpdateFromPusher () {
        channel.bind('new-comment', comment => {
            comments: [comment, ...this.state.comments]
        console.log('app subscription to event successful')

      handleChange (type, event) {
        if (type === 'author') {
        if (type === 'message') {

      * post comment to the server
      async postComment (author, message) {
        await fetch('http://localhost:8080/comment', {
          body: JSON.stringify({author, message}),
          method: 'POST',
          headers: {
            'user-agent': 'Mozilla/4.0 ',
            'content-type': 'application/json'

      handleSubmit (event) {
        this.postComment(, this.state.message)
        this.setState({author: '', message: ''})

      render () {
        return (
            <form onSubmit={this.handleSubmit.bind(this)}>
                <input type='text' value={} onChange={this.handleChange.bind(this, 'author')} />
                <br />
                <textarea type='text' value={this.state.message} onChange={this.handleChange.bind(this, 'message')} />
              <br />
              <input type='submit' value='Submit' />
            <CommentList comments={this.state.comments} />

Here, when the component gets mounted, we try to load previous comments from the server and pass that data as props to the CommentList component.

Note: please remember to updated placeholders with your pusher credentials.

Putting content on our page

Open your src/pages/index.js file which should already exist. You should replace its content with this:

    // src/pages/index.js

    import React from 'react'
    import Comment from '../components/comment'

    const IndexPage = () => (
        <h1>Leroy Aziz Sané left out of German squad for the world cup</h1>
          A lot of talks is currently ongoing about the Manchester City winger Leroy Sane being left out of the German team.
          He was a prolific player this season with Mancity winning the premier league andthe significant contribution he brought to the team in front of Goal.
          The decision by the German coach, Low to leave him out of the squad list was totally unexpected. Football really is a funny sport.
          Let me know your thoughts in the comment section below
        <Comment />

    export default IndexPage

This contains a post we made and the Comment component we imported above.

Getting data in Gatsby

Gatsby uses GraphQL for getting data. It could be from any source. There are a few files where changes need to be made to get data. We have gatsby-node.js, gatsby-browser.js, gatsby-config.js among others.

What we’re concerned about right now is gatsby-config.js. It is responsible for passing data down to our src/components/header.js component. This gets data locally from the file and it’s an easy way to initialize your application with data.

Open up your src/components/header.js file and you should see this:

    // src/components/header.js

    import React from 'react'
    import Link from 'gatsby-link'

    const Header = ({ siteTitle }) => (
          background: 'rebeccapurple',
          marginBottom: '1.45rem'
            margin: '0 auto',
            maxWidth: 960,
            padding: '1.45rem 1.0875rem'
          <h1 style={{ margin: 0 }}>
                color: 'white',
                textDecoration: 'none'

    export default Header

It takes a prop called siteTitle which was exported from the file gatsby-config.js.

Feel free to go ahead and change the value for title in gatsby.js to Football transfer buzz with Gordon Mc-Gossip'.

Setting up the server

Comments sent by users need to go somewhere, that’s what the server is for. It will save the comment, and publish it to Pusher who will trigger an update to all clients subscribed to that channel and listening for that event.

First, we’ll need to add the dependencies needed by our server.

    # for yarn users
    yarn add express body-parser cors pusher
    # for npm users
    npm i express body-parser cors pusher

Create the file server.js and add the following:

    // server.js
    const express = require('express')
    const app = express()
    const bodyParser = require('body-parser')
    const cors = require('cors')
    const Pusher = require('pusher')

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

    const port = process.env.PORT || 8080

    const pusher = new Pusher({
      appId: 'appId',
      key: 'key',
      secret: 'secret',
      cluster: 'eu',
      encrypted: true

    let comments = [
        author: 'robo',
        message: 'i totally didn\'t see that coming'

    * receive new comment from the client
    * update the comments array with the new entry
    * publish update to Pusher
    */'/comment', function (req, res) {
      const {author, message} = req.body
      comments = [...[{author, message}], ...comments]
      pusher.trigger('sport-buzz-news', 'new-comment', {author, message})

    // send all comments to the requester
    app.get('/comments', function (req, res) {

    app.listen(port, function () {
      console.log('Node app is running at localhost:' + port)

Here, we initialize Pusher with our credentials gotten from our dashboard. When we get a request on localhost:8080/comments we return all comments gotten so far and receive comments sent to POST localhost:8080/comment.

Running the app

We’ll use one of Gatsby’s helpful CLI commands to start our application. Simply run:

    # gatsby cli command
    gatsby develop

This will start our application on port 8000 and can be accessed here http://localhost:8000/.

You’ll also need to start the server by running:

    # start node server
    node server.js

Our server application will run on http://localhost:8080/ and all API calls would go here.


Gatsby allows you to export as a static content when going to production. It could prefetch your data from any data source and bundle it into the generated static file.

To do that, simply run:

    # make production build
    gatsby build

Gatsby will perform an optimized production build for your site generating static HTML and per-route JavaScript code bundles.


We’ve been able to build a simple blog application with a live comment section. This was done using Pusher and Gatsby. The repo for this tutorial lives here. Feel free to contribute.

Clone the project repository
  • JavaScript
  • Live Comments
  • React
  • Node.js
  • Channels


  • Channels
  • Beams

© 2020 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.