Building a Serverless Realtime Chat application with Pusher and NextJS

Let’s build a chat application with Pusher’s API

Why Pusher?

Pusher provides a number of affordable, easy to use APIs to add Realtime functionality to Web applications. From Realtime communication that allows users send instant messages to each other to Realtime location that allows users know the exact location of their packages anywhere in the world, Pusher makes it easy for businesses to focus on their core competencies while leveraging the power of Pusher to scale their application.

Realtime Chat Application Demo

Prerequisites

  • Local installation of Node.js
  • Local installation of Yarn
  • Basic knowledge of React and React hooks
  • Basic knowledge of Node.js

Brief overview of Pusher’s APIs

Pusher has two major products Channels and Beams to help you take your application to the next level. Channels allows for realtime communication between devices while Beams sends notifications and updates to your users devices.

Setting up Pusher

First off, we will build the backend of our chat application using NodeJS and azure functions.

Setting up our server

We’ll be building this demo using NextJS, a React framework that allows us write serverless Node.js functions within our application.

yarn create next-app --example api-routes-cors pusher-chat-demo
yarn add pusher

Setting up the Frontend

With our server setup, the next step is to setup the Client side of our application.

yarn add pusher-js axios
NEXT_PUBLIC_KEY= "YOUR_PUBLIC_KEY"

_app.js

First, we will allow users to login to the chat application using only their name. Once logged in, we’ll keep track of their name.We’ll store the state for the name inside our _app.js file. We’ll also handle the login action here before redirecting the user to the chat page itself.

pages/index.js

Our index.js is a simple file. This is where we’ll display the login input to the user allowing them to login with their name.

Chat.js

Once a user enters their name and hit enter, we redirect them to our /chat route.

Bonus

In the next part of this article, we will build on this example. We’ll use the Channels API to show which users are online and the City and Country they’re joining the chat from in Realtime.

Full-stack Engineer. Rails/Node.js/React. I love plantain chips! Reach me at Adebola.dev.