Build Live News Application With React & Nodejs

Welcome to another tutorial of PieSocket. Today we are going to learn how to make a live news application with react and node.

Let’s start by making an empty folder

Then, initialise NPM

We will use PieSocket API for real-time updates. Get your API keys from Piesocket Dashboard, select the server region closer to users of your application.

We are going to use NewsAPi. So make an API key on your News-API account.

News API lets you choose what data you wish to fetch. They have following three types

  1. Only Headlines
  2. Everything
  3. Only Sources.

Let’s start with setting up our server side code.

Create a file server.js.

And, install piesocket-nodejs library.

Put the following code in server.js the file.

In news.v2, q is a parameter for the topic of your news.

You can use more or fewer parameters according to your requirement. If you want more details on this head over to news-API Docs.

Every 5 seconds we are going to update our feed with new news topics. Nodejs code publishes the articles through PieSocket’s WebSocket Channels. Let’s write the client-side code to listen to these events.

Run your NodeJS script in the background

Let’s begin with the client-side code. Let’s make a react project using the following command. We are using React in this example but you can chose any frontend library of your choice. Not using a library will work too, you can create this client with VanillaJS.

Now install piesocket-js client library (for frontend)

Code for your client-side file:

In the code above, we have subscribed to the same channel (as on the backend), and we are listening to the same event to we get the published from backend.

Run your React project with

npm start

The application should look like this:

You can go through the whole code in Github, here.

If you have doubts about any part of this tutorial, feel free to ask in the comment section.

Hope this helps, cheers!