Real-time NextJS applications with Parse

Real-time NextJS applications with Parse

We recently published an introductory article about Next.js and parse, in which we talked about what is Next.Js, what is Parse, and how they’re a perfect match for building awesome performant applications.

If you haven’t read it yet, I highly recommend that you check it out here, since we are going to use some concepts learned in that article.

In this article, we’re going to explore how to build real-time applications using a Parse Hook for a NextJS application. Hope you enjoy 🙂

Parse hooks

Parse has a series of packages that provides us easy, real-time, offline-first interaction with the powerful Parse Server backend directly from our React application.

Currently, the available packages are:

We are going to use @parse/react-ssr to easy leverage Parse’s capability of real-time configuration using a concept called Live Queries

Live Queries

Live queries are meant to be used in real-time reactive applications, where just using the traditional query paradigm would come with some problems, like increased response time and high network and server usage. Live queries should be used in cases where you need to continuous update a page with fresh data coming from the database, which often happens in, but is not limited to, online games, messaging clients and shared to do lists. – Back4App’s Live queries documentation

If you ever had to develop a real-time application from scratch, you know that it usually comes with its fair share of overhead and it often increases the application’s complexity to be maintained and scaled.

Parse’s Live queries give us access to an easy to use robust real-time data flow.

In order to demonstrate its capabilities, we are going to use parse hooks and live queries to create a chat app with authentication!

The setup

Creating an application inside Back4App

Creating an application inside back4App is fast and easy. All you need to do is log into back4App (or create an account if you don’t have one already)

Once you are logged in, you will be redirected to the dashboard page, where you can create and manage projects. Click on the “Build new app” button and choose a name for your application.

Once your App’s creation is finished, you will be redirected to its dashboard, where you can control it

Dashboard page

From here, we need to create a Parse class, in which we are going to store our chat messages.

Go ahead and create a new class called Message. Once that class is created, add two columns to it

  • content – a string representing the message itself
  • senderName – a string representing the sender’s name
  • senderId – a string representing the sender’s id

The last task we need to accomplish is enabling live queries inside our application. To do that, click in App settings on the navigation menu, and then on server settings.

You will be redirected to the server settings page, where you need to locate the following option

Click in settings be redirected to the page where you will be able to enable this functionality in your application.

After you clicked on settings, you will be asked to configure a subdomain. The subdomain configuration is necessary to use live queries. You must also check the “activate live query” checkbox, a check all the classes in which you intend to use live queries

Starting the Next Application

I really want to focus on the core concepts of using next and parse hooks in this article, so I created an application with basic styling and functionalities.

Start by cloning it in this github repository.

PS: If you have any problem throughout this tutorial, you can checkout to a branch called “final” which contains the final version of the application and compare it to your version

Once you have cloned it, use

npm i

to install its dependencies, and then run the project using

npm run dev

The application consists of two main routes, the base path, in which the user can register or log in

auth page

and the /home path, where we have our app’s main functionality, the chat.

But for now, both the auth and the chat’s functionalities are merely illustrative and don’t actually work. Let’s change this. To add our functionalities we need to install parse and @parse/react-ssr. You can do that using the following command:

npm i --save parse @parse/react-ssr

Configuring parse

Configuring parse to be used with its hooks is incredibly easy.

inside the pages folder, navigate to _app.js

Next.js uses the _app.js component to initialize pages. You can override it and control the page initialization. Which is perfect for initializing parse.

Import initializeParse from @parse/react-ssr and then and use it to initialize Parse inside the application. initializeParse takes 3 parameters:

  • The application subdomain we configured when activating live queries
  • The app’s id
  • the App’s Js key

Both the app id and the JS key can be found inside App settings, in the Security & Keys option.

After the initialization, your component should look like this:

Handling the authentication

Currently, our index.js file (authentication route) looks like this

Although it is correctly structured, it isn’t wired up to our back end. So let’s create this connection now.

first, let’s start by simply importing Parse, with the following code

import Parse from 'parse';

After that, let’s populate the handleLogin function with the following code

Here we are leveraging Parse’s default class User and one of its auth methods to log our user.

If our log-in attempt is fortunate, we want to redirect our user to /home route.

that can be achieved using the useRouter hook, which is shipped with next by default. Add the following import statement

import { useRouter } from "next/router";

and then proceed to instantiate it

Now that we can use the router, let’s make sure our users get redirected to the chat page when they log in.

edit your handleLogin function to look like this:

But we don’t have any registered users yet, hence, the log-in function is useless for now.

Let’s fix that by creating a register user function.

The way it works is it creates a new User class and then saves the user state value to it. If the user creation is successful, the login function is called

Chat page

Now It’s time to wire our chat page up with our backend. Navigate to the index.js file, inside the pages folder.

The first thing to be done is to create a function called getServerSideProps. If you are unfamiliar with it, here’s an explanation taken directly from next’s docs

If you export an async function called getServerSideProps from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps.

Inside of it, we want to create an encodedParseQuery and then return it, so we can use this data inside our component.

All of this can be achieved through the following snippet

Now, the parseQuery prop will be available inside our component to be used.

We will use it as a parameter to useParseQuery, the hook handling our data and its real-time updates.

Import useParseQuery from @parse/react-ssr and use it like this

Results is an array of parse objects, containing our queried data. Since the message state only existed for mocking functionality purposes, delete it.

the application still expects to receive the messages array, so let’s just rename the destructured value results, to messages

we also need to change our map function, to make it work with parse objects instead of a simple array of strings.

In this snippet, we map over a list of parse objects and extract the properties id, senderName, senderId, and content from each object.

We also changed the messageClassName function which formerly formatted each even number to look like it was sent by us. Now, it compares the message’s senderId property to the logged user’s id.

Creating objects

Our messages listing is already working, but currently, they have no way of sending them. So let’s work on it.

find the handleSubmitMessage and edit its content to look like this

Now, instead of just pushing our new message to an array, we actually send it to our backend and let parse hooks do the rest of the work for us

now that we can both send and read messages, it’s time to test our application.

The auth is working just fine

auth test

But the message ordering in the chat isn’t working

Thankfully for us, that is an easy fix. Parse objects have a createdAt property by default, and we can use it to sort our array of messages.

create an order function and apply it to the mapped messages, like the following:

Now, the order of our messages is working as expected

and thankfully to parse, the application is already being updated in real-time, so if I log into my application with 2 different users (one “regular” browser window and one on incognito mode) I can send messages and see them being updated in both of my browsers, in real-time.

Making sure the user is authenticated

Until now, there’s nothing stopping someone from just navigating directly to the /home page and use the chat without being logged. This needs to be fixed.

The way we are going to fix this is by just retrieving the currently logged user with Parse.User.currentAsync(). if it returns null, that means there’s no logged user, hence we need to redirect the user to the login page.

This can be achieved by adding the current snippet to your code

PS: Don’t forget to import useRouter from ‘next/router’

One last detail

Whenever we enter our chat, we are loading all the messages ever sent in our chat, and we don’t really want to have all of our historically sent messages in the chat forever. Just imagine, having to wait for hundreds or thousands of messages to load every time you joined that room

what we want to do is get messages sent in the near past, or messages sent after the user entered the room.

this is easily achievable by twitching the query we pass to encodeParseQuery

just update the getServerSideProps function to look like this

These changes will ensure that the user only gets messages sent after the page initial load.

The final code for the home page looks like this

Wrapping up

Creating this real-time application with authentication so fast really shows the power of parse hooks + next.js.

While Next.js has awesome development tooling and provides us with all the power of React and an awesome developer experience

Parse provides robust and ready-to-use back-end capabilities, such as real-time queries, authentication and so much more with as much ease as possible.

These powerful duo is certainly going to be helpful to you in your future projects

Leave a reply

Your email address will not be published.