Chat

How to Create a Simple Web-Based Chat Application

9 min read Markus Kohler on Oct 30, 2024

Learn about the details of web-based chat applications, various chat features, how to architect your app, and finally, how to build a chat app.

Web Chat Free Demo

Chat Demo Web app

Want to get going and immediately dive into a web chat app yourself? Try PubNub's Chat SDK web chat demo, showcasing features like message threads, reactions, quoting, read receipts, unread notifications, user presence, typing indicators, user invites, @mentions, and #channel references.

You can also learn how to make a messaging app yourself by following the tutorial or you can check out the code repo on GitHub.

Build vs Buy: How to Setup the Chat App's Communication Architecture

Deciding between an in-house chat solution and a vendor-provided one is crucial.

  1. In-house development may appeal due to available developers, but it requires significant resources, time, and could face future scalability issues.

  2. Purchasing a chat solution with an software-as-a-service pricing model offers advantages but also challenges like low customizability.

  3. Plug-and-play chat provider, which can effectively add chat functionality with UI features for all sizes and simplified back-end integrations.

To achieve a fully customizable chat solution (that includes chat moderation) that can be easily integrated into any web application while saving on cost and time, it's recommended to utilize a platform that is an Infrastructure as a Service (IaaS). This cloud model lets you rent computing resources (servers, storage & networking) on a pay-as-you-go basis, avoiding upfront infrastructure costs and allowing quick scaling based on your needs.

Building a real-time chat application requires careful planning to ensure it meets the desired functionality and user experience. Here are key considerations for creating a chat app from scratch or using an IaaS service.

Real-time Chat Features

Modern live messaging applications go beyond simple messaging. Additional functionalities such as active user identification, push notifications for notifications, and message history enhance immediacy and engagement. Presence features, which show when friends or collaborators are online, are crucial for retaining users on your web app instead of losing them to other platforms.

App security (Authenticating)

Modern web development apps utilize advanced authentication systems due to the potential number of chat Channels. If you're building a chat from scratch using technologies like Socket.IO, you'll need to implement channel architecture on your server, ensuring isolated data transmission for each chat type. Only authenticated users should have access to invite others to channels.

The second layer of protection is identity authentication, typically achieved with a dynamic token system like JSON Web Tokens (JWT)). Tokens are short-lived access keys generated by the backend server, allowing users to access their invited channels. The backend must parse the token into channel-identifiable objects to specify which channels users can publish & subscribe from. A response is then sent to the client to indicate the success or failure of their access attempt based on permissions.

Communication Protocol Integration

Encryption is another security layer that needs to be applied on top of the data transmission and data storage layer for your backend app development. This depends on the transmission protocol you would like to use: you can implement either Transport Layer Security (TLS) or Web Socket Secure (WSS) protocols to achieve the functionality to run a private chat in your web application.

Using an IaaS service such as PubNub, it is built using channel separation architecture and offers an Access Manager that includes configurations for identity authentication and securing your data, so all messages and channels are protected and, when configured, will be up to the user discretion on what type of chat they would like to create.

Scalability of your Real-Time Chat Application

When designing a web-based chat application from scratch, scalability should be a top consideration to ensure the chat can handle a growing user base and increased traffic.

The backend architecture should be designed to handle many concurrent users and messages. A scalable architecture may use a distributed database, load balancers, and caching mechanisms to manage high traffic and improve performance. As the number of users and messages grows, the storage requirements will also increase. Choosing a database system that can handle large volumes of data and can be easily scaled up as needed is essential.

How to Build a Simple Web-based Chat Solution

To build the user interface of your simple chat app, download a free integrated development environment (IDE) such as Visual Studio Code and get started with your tech stack by choosing a framework, or use HTML, CSS, and Javascript. Frameworks for web apps include React or Angular, which integrate more advanced state management techniques to make the chat interface development faster.

Once you’ve downloaded the latest version of Visual Studio Code, create a project by creating .html, .css and .js files in the project directory. Usually, the core files to any vanilla javascript project are named app.js, index.html, and main.css. If you copy the absolute path of the index.html file and paste it into your browser, your code will now display and run. For a more detailed setup of a Vanilla JavaScript project, check out the Visual Studio Code tutorial. Using a framework, you can follow a tutorial for getting started with React or Angular.

Now we must choose the server-side language and hosting service we plan to use to handle network communications. For example, let's create our first web server using Node.js. Once we have installed Node.js, we want to create a Node.js project using the command “npm init” from our terminal. After creating a new project, we can open it using Visual Studio Code and follow the Node.js getting started guide for hosting a server locally.

We will want our front-end infrastructure to communicate over a WebSocket protocol with our server so we can communicate in real time between two client applications. In this case, we must familiarize ourselves with implementing and understanding WebSocket terminology inside Node.js. Install a WebSocket library, ws for WebSocket implementation, express for creating a simple HTTP server, and nodemon to track changes in our backend code and restart the server. With this setup, we can now implement the logic of creating a simple web-based chat application.

For more information on implementing WebSockets in node.js, check out our Node.js WebSocket Programming Examples.

Implementing WebSocket functionality is possible with various libraries, but PubNub offers significant advantages. It provides a fully managed infrastructure for real-time communication, eliminating the need to set up and manage your own WebSocket servers. Using PubNub server-side services saves time and effort, especially if you're not well-versed in WebSocket implementation.

Simple web-based chat application examples

We've developed a few web-based chat examples that utilize the PubNub platform that you can check out yourself.

Chat demo using the PubNub Chat SDK

A fully-featured chat application written in TypeScript using the NextJS and Tailwind frameworks. This demo showcases message threads, message reactions, quoting messages, read receipts, unread messages notifications, user presence, typing indicators, inviting users to channels, and the ability to @mention users & to #reference channels. There is some set-up required to build this tutorial yourself.

Setting Up the Next.js Project

This application is written with NextJS, so be sure to have a copy of Node.js 18.17 or later installed. To run this project yourself you will need a PubNub account.

Get Your PubNub Keys

  1. You’ll first need to sign up for a PubNub account. Once you sign up, you can get your unique PubNub keys from the PubNub Developer Portal.

  2. Sign in to your PubNub Dashboard.

  3. Click Apps, then Create New App.

  4. Give your app a name, and click Create.

  5. Click your new app to open its settings, then click its keyset.

  6. Enable the Stream Controller feature on your keyset (this should be enabled by default after you create the keyset)

  7. You can leave the Presence feature disabled, this app uses the Global Presence feature of the Chat SDK instead, as explained later.

  8. Enable the Message Persistence feature on your keyset and choose a duration

  9. Enable the App Context feature on your keyset. Check the following boxes: User Metadata Events, Channel Metadata Events, Membership Events. Uncheck the following boxes: Disallow Get All Channel Metadata, Disallow Get All User Metadata.

  10. Leave the File Sharing feature disabled. Although the Chat SDK supports sending files, this demo app does not.

  11. Copy the Publish and Subscribe keys and paste them into your app as specified in the next step.

Building and Running

  1. Clone the repository

  2. Replace the .env.samplefile with a .envfile and populate it with the publish and subscribe keys you generated in the previous step.

  3. cd chat-sdk-demo-web

  4. yarn install

  5. yarn dev

  6. You can now navigate to localhost:3000 in your browser

You can learn more about the application in the GitHub readme repository.

Build Chat in 10 Lines of Code

With PubNub, you can see in this demo how easy is it to create a JavaScript chat app in fewer than 10 lines of code using PubNub. This demo features basic message publishing, as well as subscriptions to listen for messages from other participants.

Installing / Getting Started

To run this project yourself you will need a free PubNub account.

Get Your PubNub Keys

  1. You’ll first need to sign up for a PubNub account. Once you sign up, you can get your unique PubNub Pub/Sub keys from the PubNub Developer Portal.

  2. Sign in to your PubNub Dashboard.

  3. Click Apps, then Create New App.

  4. Give your app a name, and click Create.

  5. Click your new app to open its settings, then click its keyset.

  6. Copy the Publish and Subscribe keys and paste them into your app as specified in the next step.

Building and Running

  1. You'll need to run the following commands from your terminal.

  2. Clone the GitHub repository.

    git clone https://github.com/PubNubDevelopers/JavaScript-Simple-Chat.git

  3. Navigate to the application directory.

    cd JavaScript-Simple-Chat

  4. Add your pub/sub keys to index.html, replacing the existing 'demo'keys.

Getting started with PubNub for your web-based chat application

PubNub is an IaaS service that can achieve a fully customizable chat solution using one of our SDKs that can be integrated into your web application quickly and cost-effectively. You can leverage PubNub to build real-time messaging features into their application. Ultimately, this strategy can help companies save time and money while delivering a high-quality chat solution to their customers.

PubNub has the following features built-in into its API and can meet the specific needs of your applications.

  1. Publish: Send messages whenever user input is updated, such as text updates, emoji reactions, sent files, and other complex metadata.

  2. Subscribe: Receive new messages to refresh users' screens.

  3. Presence: Update and detect the online status of users.

  4. Message Persistence: Display any received messages once users log in to the app or track project and document revisions.

  5. Mobile Push Notifications: Notify mobile users who are away from the app about any chat messages, project updates, or application updates.

  6. App Context: Store information about your user in one place without setting up or calling your database.

  7. Access Manager: Restrict access for private conversations, channel rooms, documents, and projects for specific users.

  8. Functions: Translate messages, censor inappropriate messages, announce the arrival of new users, and notify other users of mentions.

  9. Events & Actions: Centrally manage events in your application’s ecosystem and trigger business logic without code.

To begin using PubNub to power your web-based real-time chat app, you must first create a PubNub account and download PubNub’s JavaScript SDK. The SDK integrates seamlessly into your application and allows you to connect to PubNub’s real-time communication platform.

  1. Sign in or create an account to create an app on the Admin Portal and get the keys to use in your application. Learn how to do so by following this how-to on creating keys.

  2. Download the JavaScript Chat SDK or the JavaScript Core SDK by following the instructions in the documentation to install any necessary PubNub dependencies for your messaging app.

  3. Follow the Chat SDKs getting started documentation to configure a PubNub object to begin publishing and subscribing to channels.

Benefits of live chat app

The increasing reliance on chat applications is due to their numerous benefits. For example, they allow faster decision-making, improved collaboration, and enhanced productivity. Moreover, chat platforms record all conversations, making tracking progress easier and referring to previous discussions. Additionally, these apps are becoming more sophisticated, incorporating features like video and voice calls, and screen & file sharing: chat applications have become indispensable tools for modern communication and collaboration. Whether it's private chat, group chat, or large-scale chat, adding personalized chatting features to your app can help ensure your users have a memorable experience.

Why Build a Web Chat Application

There is a high demand for new and innovative chat software that cater to specific needs. Simple web-based chat applications can be customized to suit different industries and businesses, providing a unique platform for users to communicate and collaborate. For example, live chat designed for healthcare professionals can incorporate specific features such as secure messaging (HIPAA Compliant) and video consultations, making it more efficient and effective for medical practitioners.

Building a chat application for your business can also provide lucrative business opportunities, potentially generating revenue through advertisements, subscriptions, and in-app purchases. Furthermore, as technology advances, the possibilities for chat applications are endless, with the potential to incorporate cutting-edge features such as generative AI and virtual reality.

Happy coding!