How to stream user tweets with Zapier and React
You will need Node 6+ installed on your machine. Some experience of React will be helpful.
In this tutorial, we’ll explore how Pusher Channels can be used in conjunction with Zapier to display updates to a user’s Twitter feed on a webpage. If you want to play around with the code as you read this tutorial, visit this GitHub repository which contains the final version of the code for you to check out and run locally.
Prerequisites
Prior experience with building React and Node.js applications is required to complete this tutorial, but you don’t need to know how to use Pusher Channels. You also need to have Node.js (version 6 and later) as well as npm (version 5 or later) installed on your machine. You can use the commands node -v
and npm -v
to see which versions of Node and npm you have installed.
Getting started
Create a new folder for this project in your filesystem. You can call it tweet-stream
or any other name that you prefer. Open a new terminal window and cd
into the new directory you just created, then run npm init -y
to initialize the project with a package.json
file.
Next, run the following command to install all the dependencies we’ll be needing to build the server component of the application:
npm install express body-parser cors dotenv pusher -S
Once the installation completes, create the following files in the root of your project directory: server.js
and variables.env
.
Sign up for Pusher
Before we can utilize the features of Pusher Channels in our application, we need to sign up for a free Pusher account. Once your account is created, select Channels apps on the sidebar, and hit Create Channels app to create a new app. Retrieve your credentials from the API Keys tab, and then add the following to the variable.env
file you just created.
// variables.env
PORT=5000
PUSHER_APP_ID=<your app id>
PUSHER_APP_KEY=<your app key>
PUSHER_APP_SECRET=<your app secret>
PUSHER_APP_CLUSTER=<your app cluster>
Set up the server
Open up server.js
in your text editor and paste in the following:
// server.js
require('dotenv').config({ path: 'variables.env' });
const express = require('express');
const cors = require('cors');
const Pusher = require('pusher');
const bodyParser = require('body-parser');
// Create an express app
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
encrypted: true,
});
app.post('/', (req, res) => {
console.log(req.body);
});
app.set('port', process.env.PORT || 5000);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
As you can see, we’ve set up just the one route where new tweets will be posted to. For now we’re just logging the request body to the console, but we’ll revisit this section in the later parts of the tutorial.
You can start the server by running node server.js
in the terminal. It should now be running on port 5000.
Expose your local server to the world with ngrok
To make your local server is accessible to the outside world, you can use a service like ngrok. Visit the ngrok website to find out how to install and set up ngrok on your computer. Once you have it installed, start an HTTP tunnel on port 5000 by running the following command in a new terminal window:
./ngrok http 5000
If your webhook server is listening on another port, make sure to provide the correct port when starting the HTTP tunnel. You will be given a couple of URLs but you only need the last one which is on the secure (HTTPS) protocol.
Sign up for Zapier
Zapier is a service that allows you to integrate between several applications. To use Zapier, you need to sign up for an account. Once your account is created, go here and click the Make a Zap! button to create your first Zap.
Under Choose a Trigger App, select Twitter and choose User Tweet under Twitter Trigger.
Hit the Continue button to move on to the next step. Connect a Twitter account that will be used for this Zap. You can use your existing Twitter account, or create a new one if you prefer. Once you have connected account, select it and hit Save + Continue.
On the screen that says Pick A Sample To Set Up Your Zap, before you click Pull in Samples, make sure there is a recent enough tweet on the account you set up. Otherwise, send a tweet out before clicking the button.
You should see the following screen once a sample tweet has been pulled from your Twitter account. Just hit the Continue button.
You need to setup an action step. Click the link highlighted in the screenshot below to add an action app.
Under Choose an Action app select Webhooks by Zapier Action, then select POST under the CREATE heading and click the Continue button.
You will be asked to provided a URL under Set up Webhooks by Zapier POST. Copy the URL received from ngrok into the input field. Under advanced options, set the Payload type to Json then hit the Continue button.
On the next page, hit Send Test to Webhook by Zapier. This will send a post request to your local server along with the payload of the sample tweet pulled in earlier in the request body. Check the terminal window where the server is running. You should see some JSON output in the terminal.
Finally, hit Skip test on the left hand side and Finish on the right. You will be redirected to a page confirming the successful setup of your first Zap.
The 15 minute interval is a limitation of Zapier’s free and entry level plans. With a paid plan, you can take it to as low as 5 minutes.
Create the application frontend
Let’s work on the app frontend a bit. We need to install the create-react-app
package globally so that we can use it to bootstrap a new React app. Use the following command below to install create-react-app
:
npm install create-react-app -g
Next, cd
in to your project directory and run create-react-app client
to create a new React app in a new directory called client
. Once the installation process completes, cd
into the newly created client
directory and run yarn start
to start the development server. The application will be available for you to view it at http://localhost:3000.
Launch another terminal window, and cd
into the client
directory. Then run the following command to install the other dependencies we’ll be using to build the React app.
npm install react-timeago pusher-js -S
Next, open up client/src/App.js
in your favorite text editor and change its contents to look like this:
// client/src/App.js
import React, { Component } from 'react';
import Pusher from 'pusher-js';
import TimeAgo from 'react-timeago';
import './App.css';
class App extends Component {
state = {
tweets: [],
};
componentDidMount() {
const pusher = new Pusher('<your app key>', {
cluster: '<your app cluster>',
encrypted: true,
});
const channel = pusher.subscribe('tweets');
channel.bind('new-tweet', data => {
const { tweets } = this.state;
tweets.push(data.payload);
this.setState({
tweets,
});
});
}
render() {
const { tweets: tweetArr } = this.state;
const Tweet = (tweet, index) => (
<div className="tweet" key={index}>
<p className="user">
<span className="screen-name">{tweet.user__name}</span>
<span className="username">{tweet.user__screen_name}</span>
</p>
<p className="tweet-text">{tweet.text}</p>
<div className="meta">
<div>
<span className="retweets">Retweets: {tweet.retweet_count}</span>
<span className="likes">Likes: {tweet.favorite_count}</span>
</div>
<a href={tweet.url}>
<TimeAgo date={tweet.created_at} />
</a>
</div>
</div>
);
const tweets = tweetArr.map((tweet, index) => Tweet(tweet, index));
return (
<div className="App">
<header className="App-header">
<h1>Tweets</h1>
</header>
<main className="tweets">{tweets}</main>
</div>
);
}
}
export default App;
The componentDidMount()
lifecycle method houses the logic for displaying new tweets on the page. We’re opening a connection to Channels using the subscribe()
method which allows us to subscribe to a new channel called tweets
. Then, we listen for the new-tweet
event on the tweets
channel using the bind
method and update the application state once we receive a tweet update.
Don’t forget to retrieve your Channels credentials from the API Keys tab in the dashboard, and then replace the <your app key>
and <your app cluster>
placeholders in App.js
with the appropriate values.
Add the styles for the app
Let’s add the styles for the app’s frontend. Open up client/src/App.css
in your editor and replace its contents with the following styles:
// client/src/App.css
body {
font-family: Helvetica, "Helvetica Nueue", sans-serif;
}
.App {
text-align: center;
}
.tweets {
width: 100%;
max-width: 700px;
margin: 30px auto;
}
.tweet {
margin-bottom: 20px;
border: 1px solid #ccc;
padding: 15px;
text-align: left;
}
.screen-name {
font-weight: bold;
display: inline-block;
margin-right: 10px;
}
.username::before {
content: '@';
}
.retweets {
display: inline-block;
margin-right: 10px;
}
.meta {
display: flex;
justify-content: space-between;
}
Trigger updates from the server
Inside the server.js
file, change the root route to look like this:
// server.js
app.post('/', (req, res) => {
pusher.trigger('tweets', 'new-tweet', {
payload: req.body,
});
});
Zapier will hit this route for each new tweet that is posted to the Twitter account you connected, and include the tweet payload in the request body. We can then trigger a new update on the tweets
channel with the tweet payload included.
Kill the server using Ctrl-C
and run node server.js
again from the root of your project directory. Then send a few tweets using your Twitter account. After about 15 minutes, you should see the new tweets on the page.
You can also trigger the update manually by going to the Zapier dashboard, find the Zap you created and hit the Run button as shown the screenshot above.
Wrap up
I have explained how to set up Zapier to get fetch user tweets every 15 minutes and how to display new updates on a webpage with Pusher Channels. If you want to dig into other things you can do with Channels, make sure to check out its exhaustive documentation. To grab the complete code used in this tutorial, please visit this GitHub repository.
12 December 2018
by Ayooluwa Isaiah