How to build a real-time chat app

Create a real time chat application that utilises some of the most cutting edge front end technology available today.

Angular app on Github Messaging Angular app source code

Angular API on Github Messaging GraphQL api source code

Note: This guide shows you how to build an Angular app with GraphlQL. An example React app is also available

React app on Github Messaging React app source code

What we're going to build

Messaging web application built with Angular and GraphQL Follow this tutorial to build a real-time chat application. Once you download and install the Slack application to your PC, laptop and/or phone devices, allow anyone using the web-based chat app to instantly message you and get notified immediately through any of the downloaded Slack apps on your devices.

The best part is it's completely free. You don't have to make a purchase to complete this tutorial.

Contents

Technology stack

Overview of concepts

A brief introduction to some core concepts. Feel free to skip ahead if you are familiar with some of the following concepts. If you aren't familiar with these, I highly recommend reading through each to understand the underlying strategies that the frameworks in this tutorial are based on. This will help in understanding the motivations behind each approach.

Read about Redux data flow architecture

Overview: GraphQL API schemas and the redux data store

State in applications can be managed via a Redux data store. GraphQL is concerned with defining the types of data that can be held in the Redux store. A GraphQL schema will define the shape of objects that need to be created and sent to the client (web-browser) from the server. Typically just one endpoint is needed for GraphQL to serve all types of data.

A customised request can be sent from the client to the GraphQL endpoint. This empowers applications to retrieve all data needed in one concise asynchronous request, which maps very well to user events. GraphQL will then analyse the request and attempt to start building a response that fulfills the description of data specified in the request. Data can be retrieved from a database, session, another service or multiple services to build a normalised response Graph for clients to consume. The great thing is that the shape of a response is purposefully designed to look very similar to the shape of the request it was responding to.

Things you'll need:

Prior knowledge

Software

Software and adjacent system setup

We will need to setup some software and third-party services before we can start development.

Slack

If you haven't got a Slack user account, you'll need to create one at: https://api.slack.com (this will require several steps including email verification but should be pretty straight forward) and create a new Slack workspace https://slack.com/get-started?entrypoint=redirectflow#/createnew. When creating the workspace, make sure to choose the Free option.

Once your workspace has been created, go back to https://api.slack.com/apps and click 'Create an app'. Type your app name and select your new workspace click through steps using defaults. Once you've created the app, make sure your web app is selected (this will be indicated by the name shown in the top left corner).

Navigate to the 'Basic Information' page from the left-hand navigation and click Generate Tokens and Scopes under App-Level Tokens. Add a token name and click Add scope. From the dropdown select the following scope:

  • connections:write

Copy the token that's generated, we'll need this for later.

Next navigate to Event Subscriptions and toggle on Enable Events. This will allow the app to use Socket Mode (WebSockets),

Navigate to the 'Basic Information' page from the left-hand navigation and click 'Add features and functionality'. Click 'Bots' and on the next page click 'Add a bot user'. Enter the details you want for the bot (can leave defaults) and click 'Add Bot User'.

In the left-hand navigation click 'OAuth & Permissions' and scroll down to the section 'Scopes'. Click 'Add an OAuth Scope', then search and add the following Bot Token Scopes:

  • app_mentions:read
  • channels:history
  • channels:manage
  • channels:read
  • chat:write
  • groups:history
  • groups:write
  • im:history
  • users.profile:read
  • users:read

In the left-hand navigation click Install App and then Install to <your workspace>. Allow the app access. On the page that follows, copy the bot token, we'll need this later.

Before running your GraphQL API each time, make sure the following environment variables exist

Set the following environment variables with the tokens you copied:

App token: SLACK_APP_TOKEN=xapp-...

Bot token: SLACK_RTM_ACCESS_TOKEN=xoxb-

One variable will be needed for HTTP access to certain resources and the other for real-time-messaging communication over Websockets.

In your email inbox that you used to sign up with Slack, you should have been given a URL for your workspace. Make note of this as well as your user name and password. These will be needed to log in to Slack to see messages sent from users of the application we are going to build.

Our app

One of our aims for the project is to separate as many parts of the application as possible to enable us to easily swap and change them as and when we want.

It's worth taking some time to consider what a message actually is, the relationship it has to the person who created it. By accurately defining what a message consists of, we can find an overlapping scope of requirements to easily identify potential compatibility for integration of other third party services such as WhatsApp or Facebook.

We will write our application to allow for this flexibility of integration.

Part 1

App setup

First we will need to create a folder for our project to hold our front end web application and the web api server that will serve data to our application.

After you've created your project folder, open a command-line or terminal window and change directory to your new project folder

cd <project-folder-path>

(replace <project-folder-path> with a path to your new directory).

Create the Angular app

Angular CLI

The Angular CLI will be the framework we'll use to build out the front end application. To install, run the following command:

npm install -g @angular/cli

Now you have the Angular CLI installed, run the following Angular CLI command to setup a new workspace:

ng new

Call the project web-app and choose SCSS as the stylesheet format (CSS preprocessor). Say no to server-side rendering (SSR/SSG) as we don't need it for this app, and skip any optional prompts, such as those for AI tooling. Routing is set up for you by default, so there is no routing prompt to answer.

The Angular CLI will create and setup a directory after your project name ready for you to build your Angular application. Inside there are a lot files created. The CLI will setup a git repository for version control, initialise an npm package for managing project dependencies, include numerous configuration files, create a directory called 'src' with some essential Angular application files with more configuration files that you can customise, create a public folder for saving images, fonts and other static media, set up unit testing with Vitest and bootstrap the app from a standalone root component (src/app/app.ts), configured through src/app/app.config.ts and src/app/app.routes.ts. There are no NgModules and no zone.js to worry about.

This will give you everything you need to get started developing with Angular. For more further reading about the artifacts created by the Angular CLI refer to the Angular CLI documentation

Test and confirm you have everything setup correctly by running the application with the following commands.

cd web-app

Then

ng serve

You should get a message in your terminal that says 'Application bundle generation complete'. You'll now be able to see the default Angular page for web-app in your web browser by navigating to http://localhost:4200.

Read A brief overview of Angular to get to grips with some Angular core concepts.

Apollo Client

We will use a framework for managing our application state. Apollo Client for Angular will manage API requests and responses from the server and primarily handle delivery of data to and from the application. Apollo uses GraphQL to describe the shape of application data. Add this by using the Angular CLI command and a util we'll use for setting up GraphQL websockets:

ng add apollo-angular

npm install graphql-ws

This command will install the Apollo Angular client (apollo-angular) and update the app.config.ts file to configure the graphQL endpoint but we'll replace this with own configuration.

We'll keep our own Apollo configuration in a core folder instead, so you can delete any generated graphql.provider.ts file (and its entry in app.config.ts). First we need somewhere to store the location of our GraphQL server. New projects don't come with an environments folder, so create a small interface to describe our environment settings and an environment file that uses it:

File path icon web-app/src/environments/environment.model.ts
export interface Environment {
  production: boolean;
  graphQLRoot: string;
}
File path icon web-app/src/environments/environment.ts
import { Environment } from './environment.model';

export const environment: Environment = {
  production: false,
  graphQLRoot: 'localhost:4123',
};

Now create the Apollo configuration. Apollo Angular calls the function we give it when the app starts up, and the function can use Angular's inject() to get the HttpLink service for talking to the server:

File path icon web-app/src/app/core/apollo.ts
import { inject } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import { ApolloClient, ApolloLink, InMemoryCache, split } from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { getMainDefinition } from '@apollo/client/utilities';
import { HttpLink } from 'apollo-angular/http';
import { Kind, OperationTypeNode } from 'graphql';
import { createClient } from 'graphql-ws';

import { environment } from '../../environments/environment';

const clientId = 'cid:' + Math.random() * Math.pow(10, 16);

/**
 * Factory for `provideApollo()`. Runs in an injection context.
 */
export function apolloOptions(): ApolloClient.Options {
 return {
  link: createServerLink(inject(HttpLink)),
  cache: new InMemoryCache(),
 };
}

function createServerLink(httpLink: HttpLink): ApolloLink {
 const http = httpLink.create({
  uri: `http://${environment.graphQLRoot}/graphql`,
  headers: new HttpHeaders({ clientid: clientId }),
  withCredentials: true,
 });

 /**
  * Speaks the `graphql-transport-ws` protocol served by `graphql-ws`'s `useServer()`.
  * `connectionParams` is exposed to the server's `onConnect` as `ctx.connectionParams`.
  */
 const ws = new GraphQLWsLink(
   createClient({
     url: `ws://${environment.graphQLRoot}/graphql`,
     connectionParams: { clientId },
     retryAttempts: Infinity,
     shouldRetry: () => true,
   }),
 );

 // Subscriptions go over the WebSocket, queries and mutations over HTTP
 return split(
   ({ query }) => {
     const definition = getMainDefinition(query);

     return (
       definition.kind === Kind.OPERATION_DEFINITION &&
       definition.operation === OperationTypeNode.SUBSCRIPTION
     );
    }, ws, http,
 );
}

Finally, register the configuration with provideApollo() in the application config. HttpLink is built on Angular's HttpClient, so we provide that too:

File path icon web-app/src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { provideApollo } from 'apollo-angular';

import { routes } from './app.routes';
import { apolloOptions } from './core/apollo';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes),
    provideHttpClient(),
    provideApollo(apolloOptions),
  ],
};

You may have guessed, graphQLRoot is the location of our GraphQL server. All we need to do is specify one endpoint location to communicate via HTTP with the server for data. Later we will extend this configuration with a separate websocket connection (using the graphql-ws library) for real-time instant messaging.