Add a chat widget to your Gatsby blog
Some knowledge of React will be helpful when following this tutorial.
Gatsby is a static-site generator which uses modern web technologies such as React and Webpack. It can generate blazing-fast static sites from Markdown, JSON, APIs, and CMSs like Wordpress and Drupal.
In this tutorial, we’re going to take a look at how we can add a realtime chat feature to a Gatsby blog using Pusher. This tutorial assumes that you’re new to Gatsby but have a little bit of knowledge on React.
What you’ll create
You’ll be creating a realtime chat component using React and Pusher. This allows visitors of your blog to chat with each other. Each blog post will serve as a unique chat room. This means that messages sent from “blog post A” will only be viewable from that page. Here’s what the final output will look like:
You can find the source code for this tutorial on this Github repo.
Install Gatsby
The first thing that you need to do is to install the Gatsby command line tool:
npm install -g gatsby-cli
This allows you to create a Gatsby site from the command line.
The gatsby-cli comes with a default template for starting out a Gatsby site, but we’re going to use the Gatsby starter blog instead. This is because the default template doesn’t really come with the plugins that will allow us to build a blog from markdown files. We’re using Markdown since it is the most common format for building static sites.
Here’s how you can tell Gatsby to use the “Gatsby starter blog” as the template:
gatsby new gatsby-blog https://github.com/gatsbyjs/gatsby-starter-blog
Once that’s done, you can now start developing using the develop
command:
gatsby develop
This spins up a local server which you can access at http://localhost:8000
from your browser. This automatically reloads as you make changes to the files in the src
directory or the config file (gatsby-config.js
).
Create a Pusher app
In order to use Pusher, you first need to create a new Pusher app. Select React as the front-end tech and Node.js as the back-end tech.
If you don’t have a Pusher account yet, you can sign up here. Pusher’s sandbox plan is free and is very generous when it comes to the number of messages you can send.
Once created, go to the app settings page and enable client events:
This allows us to directly send messages from the client-side without server intervention, though Pusher requires an authentication server before client events can be sent. This is a security feature in order to ensure that the users who are sending messages are really genuine users of the app. In the next section, you’ll learn how to create the server.
Create the auth server
To create an auth server, start by creating a new folder outside of your Gatsby blog. Once created, navigate inside that directory and install the following packages:
npm install express body-parser pusher
Next, create a server.js
file and import the packages you just installed:
var express = require('express');
var bodyParser = require('body-parser');
var Pusher = require('pusher');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Since the blog will be on a different domain from the auth server, we need to enable CORS so that it can accept connection from any domain:
// enable cross-origin resource sharing
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Next, add the code for connecting to Pusher. I’ll explain later how the values for the configuration options are supplied. For now, just know that they’re being loaded as environment variables:
var pusher = new Pusher({ // connect to pusher
appId: process.env.APP_ID,
key: process.env.APP_KEY,
secret: process.env.APP_SECRET,
cluster: process.env.APP_CLUSTER,
});
Next, add a route for checking if the server is running:
app.get('/', function(req, res){ // to test if the server is running
res.send('all green');
});
Lastly, add the routes for authenticating users. Later on, the Chat component will hit this route every time a visitor views a blog post:
// to authenticate users
app.post('/pusher/auth', function(req, res) {
var socketId = req.body.socket_id;
var channel = req.body.channel_name;
var auth = pusher.authenticate(socketId, channel);
res.send(auth);
});
var port = process.env.PORT || 5000;
app.listen(port);
As you have seen, there’s really no authentication going on. This exposes your Pusher app to potential misuse because anyone can just use your Pusher App ID and it won’t be verified that the request came from your blog. Here’s some code that will allow you to verify where the request originated from. Add this to your Pusher auth handler, right before the pusher.authenticate
call to check if the request is valid or not.
var origin = req.get('origin');
if(origin == 'YOUR BLOG DOMAIN NAME OR IP'){
// authenticate the request
}
Deploy the auth server
We’ll be using Now to deploy the auth server. You can install it with the following command:
npm install -g now
Navigate to the folder where you have the server.js
file and execute now
. This will ask you to enter and verify your email.
Once verified, you can add the Pusher app config to now’s secrets. Be sure to replace the values on the right side with the actual Pusher app config.
now secret add gatsby_app_id YOUR_PUSHER_APP_ID
now secret add gatsby_app_key YOUR_PUSHER_APP_KEY
now secret add gatsby_app_secret YOUR_PUSHER_APP_SECRET
now secret add gatsby_app_cluster YOUR_PUSHER_APP_CLUSTER
After that, you can already deploy the auth server:
now -e APP_ID=@gatsby_app_id -e APP_KEY=@gatsby_app_key -e APP_SECRET=@gatsby_app_secret APP_CLUSTER=@gatsby_app_cluster
The values on the left side (e.g. APP_ID
) are the names for the environment variable and the values on the right side are the names you gave to the secret (e.g gatsby_app_id
) earlier. This allows the auth server to access it via process.env.APP_ID
.
Once deployed, you should be able to access the URL returned by now.
Create the chat component
Now you’re ready to work with the Chat component. First, navigate inside the Gatsby blog folder and install the dependencies:
npm install --save pusher-js slugify random-animal-name-generator react-timeago
Here’s a summary of what each one does:
pusher-js
- for communicating with Pusher.slugify
- for creating a machine-friendly channel name for Pusher.random-animal-name-generator
- for generating a random animal username for each user in the chat room.react-timeago
- for creating human-friendly timestamps (e.g 3 minutes ago).
Once everything is installed, create an index.js
file in the src/components/Chat
directory. This will serve as the main file for the Chat component.
Start by importing the packages you just installed, as well as the MessageList
component which we’ll be creating later:
import React from 'react';
import PropTypes from 'prop-types';
import Pusher from 'pusher-js';
import slugify from 'slugify';
import randomAnimal from 'random-animal-name-generator';
import MessageList from './MessageList'; // the component for listing messages
import './style.css';
Next, create the Chat component:
class Chat extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this); // for updating the message being typed by the user
this.onSubmit = this.onSubmit.bind(this);
this.state = {
message: '', // the message being typed by the user
messages: [] // the messages that will be displayed by the MessageList component
}
this.user = randomAnimal(); // generate random animal name
}
// next: add code for componentWillMount()
}
Just before the component mounts, connect to Pusher and subscribe to the channel for the current blog post in which the component is used. Later on, we’ll be importing this component in the template used for rendering blog posts. It will then use the title of the blog post as the channel name, which means that each blog post will be a separate chat room. Only those who are currently accessing a specific blog post can send and receive messages on it.
componentWillMount() {
this.pusher = new Pusher('YOUR-PUSHER-APP-KEY', {
authEndpoint: 'https://YOUR-AUTH-SERVER-ENDPOINT',
cluster: 'YOUR APP CLUSTER',
encrypted: true // whether the connection is encrypted or not
});
// subscribe to the channel for this specific blog post
var channel = 'private-' + slugify(this.props.title);
this.post_channel = this.pusher.subscribe(channel);
}
// next: add componentDidMount
Once the component is mounted, we want to listen for when a message is sent to the channel we just subscribed to. The function specified as the second argument gets executed every time someone viewing the same blog post sends a message. When this happens, we update the state so the UI is updated.
componentDidMount() {
this.post_channel.bind('client-on-message', (message) => {
message.time = new Date(message.time); // convert to a date object since its converted to a string when sending the message
// update the state to include the new message
this.setState({
messages: this.state.messages.concat(message)
});
});
}
// next: add render()
Next, render the actual component:
render() {
return (
<div className="chatbox">
<div className="post-single">
<div className="post-single__inner">
<h1>Chat Component</h1>
<form onSubmit={this.onSubmit}>
<input type="text" className="text-input" placeholder="Type your message here.."
value={this.state.message}
onChange={this.handleChange} />
</form>
{
this.state.messages &&
<MessageList messages={this.state.messages} />
}
</div>
</div>
</div>
);
}
// next: add handleChange() function
Update the state when the value of the text field for entering the message changes:
handleChange(e) {
var message = e.target.value;
this.setState({
message: message
});
}
When the user presses the enter key, get the current value of the text field then create an object containing the name of the user, the message and the time it was sent. Once created, send it using the trigger
function. This will then cause the event listeners on any other browser tab with the same blog post open to be triggered.
onSubmit(e) {
e.preventDefault();
let text = this.state.message;
let message = {
by: this.user,
body: text,
time: new Date()
};
this.post_channel.trigger('client-on-message', message);
this.setState({
message: '',
messages: this.state.messages.concat(message)
});
}
// next: add prop types
Don’t forget to specify the required props for this component:
Chat.propTypes = {
title: PropTypes.string.isRequired
};
export default Chat;
Next, create the MessageList component. This displays the list of messages sent by the users within a specific blog post:
import React from 'react';
import ReactDOM from 'react-dom'; // for working with the DOM
import PropTypes from 'prop-types';
import TimeAgo from 'react-timeago'; // for displaying human-friendly time
class MessageList extends React.Component {
constructor(props) {
super(props);
this.renderMessages = this.renderMessages.bind(this);
}
// next: add the render() method
}
The render()
method calls the method for rendering the messages. Below it is a div which acts as the anchor for scrolling to the bottom of the chat component. We’re setting its ref
to this.messagesEnd
so we can refer to this particular div whenever we need to scroll to the bottom of the component.
render() {
return (
<div className="messages">
{ this.renderMessages() }
<div ref={(el) => { this.messagesEnd = el; }}></div>
</div>
);
}
// next: add the renderMessages() function
The renderMessages()
function loops through the array of messages and displays them one by one:
renderMessages(){
return this.props.messages.map((msg, index) => {
return (
<div className="msg" key={index}>
<div className="msg-from">{msg.by}</div>
<div className="msg-body">{msg.body}</div>
<div className="msg-time">
<TimeAgo date={msg.time} minPeriod={60} />
</div>
</div>
);
});
}
// next: add the scrollToBottom() function
The scrollToBottom()
function selects the div at the bottom of the Chat component and scrolls down to it:
scrollToBottom() {
const node = ReactDOM.findDOMNode(this.messagesEnd);
node.scrollIntoView({ behavior: "smooth" });
}
Everytime the component is updated, we want to scroll to the bottom of it. This way the latest message is always visible:
componentDidUpdate() {
this.scrollToBottom();
}
// next: add prop types
Again, don’t forget to include the prop types:
MessageList.propTypes = {
messages: PropTypes.arrayOf(
React.PropTypes.shape({
by: PropTypes.string.isRequired,
body: PropTypes.string.isRequired,
time: PropTypes.instanceOf(Date).isRequired
})
)
};
export default MessageList;
Lastly, create a style.css
file and add the following:
.chatbox {
width: 500px;
padding-bottom: 50px;
margin: 0 auto;
}
.text-input {
padding: 10px;
width: 100%;
}
.msg {
padding: 10px 0;
border-bottom: 1px solid #f7f7f7;
}
.msg-from {
font-weight: bold;
}
.msg-time {
font-size: 13px;
}
.msg-body {
font-size: 18px;
}
.messages {
min-height: 0;
max-height: 400px;
margin-top: 30px;
overflow: auto;
}
Add the chat component to blog posts
Now you’re ready to actually add the component to the blog post page. For this particular starter theme, the file you need to edit is src/templates/blog-post.js
.
At the top of the file, include the Chat component:
import Chat from '../components/Chat';
Then render it right after the Bio component, passing in the title of the blog post as a prop:
<Chat title={post.frontmatter.title} />
Deploying the blog
We’re going to use surge.sh. Surge is a service specifically created for hosting static websites for free. All you have to do is install the Surge command line tool:
npm install -g surge
Next, tell Gatsby to build the static site:
gatsby build
Once it’s done building the site, you can now deploy it using surge:
surge public your-blogs-name.surge.sh
The surge
command accepts the name of the folder in which the static files are stored, and the domain name as its options. Note that by default you’re stuck in the surge.sh
subdomain.
If you want to use a custom domain, you can simply add a CNAME file which contains the custom domain name inside the public
directory.
Once it’s done uploading, you may now access the site on the URL that you specified.
Conclusion
That’s it! In this tutorial you’ve learned how to create a realtime chat component for your Gatsby blog. As you have seen, adding realtime features to your Gatsby blog is really made simple by using Pusher.
1 June 2018
by Wern Ancheta