Build a Chat Application in JavaScript in 10 Lines of Code
PubNub Chat provides a high-performance real-time messaging infrastructure with robust APIs designed for seamless data transmission across any application. Leverage our platform to quickly develop a chat solution with enterprise-level security, scalability, and reliability. PubNub abstracts away the complexities of setting up and maintaining your messaging infrastructure & backend logic (routing and delivery), allowing you to focus on building and optimizing your application while solving core business challenges for your users.
Why Use JavaScript for Chat?
JavaScript dominates modern web development, with over 98% of websites using it as their client-side scripting language. JS is a leading choice for real-time chat applications due to its event-driven, non-blocking architecture, which ensures seamless communication without performance bottlenecks. Its ability to handle asynchronous events efficiently makes it well-suited for dynamic, interactive messaging systems. The WebSocket API enables persistent, low-latency connections, while platforms like PubNub provide scalable infrastructure for managing real-time messaging across global users. Firebase Realtime Database offers instant data synchronization with minimal backend setup, and WebRTC enables direct peer-to-peer communication for rich media interactions. With strong ecosystem support and widespread adoption, JavaScript remains the go-to language for building fast, responsive chat applications.
Follow this tutorial to learn how to create a live chat app with only ten lines of JS code using the PubNub JavaScript SDK, without worrying about the low level details.
Build Chat application in 10 Lines of Code
There are two methods available for you to try out this software demo:
- Our interactive 10-chat demo will take you through this mini-chat room application step-by-step. This demo is the same code you can copy below with an interactive walkthrough.
- Clone the GitHub repository to see how the communication application works behind the scenes and build your own chatting features.
Below is a simple demonstration how it might look:
How to Build HTML Real-Time Chat App in 10 Lines of Code
To start your real-time messaging app, you'll need to obtain the API keys necessary to connect to the PubNub platform: the publish and subscribe keys. You can get your own set of free API keys by following these steps:
- Log in to the Admin Portal.
- Click on the Apps tab on the left-hand side.
- Click on the “Create New App” button to create a new application. Give the application a name and click the “Create” button.
- Click on your newly created app. You will be brought to the keysets page for this application. Note that each app created automatically generates a new keyset (authentication credentials consisting of a Publish Key, Subscribe Key, and Secret Key) for you. Still, you will be creating a new keyset to enable specific features.
- Click the “Create New Keyset” button on the upper right side of the portal.
- A pop-up appears. Give the keyset a name and click the “Create” button.
- Click on the newly created keyset.
- Copy the Publish and Subscribe Keys by clicking on the copy icons next to each key field.
Once you've obtained the API keys, create the file index.html and save it. In index.html, integrate the PubNub SDK into your project using a content delivery network (CDN).
Then, configure PubNub by adding the following code to the file for your application.
note: addListener
listens for messages but doesn't account for things like presence events, errors, or connection status changes, which are relevant in real-world production applications.
Be sure to replace PUBNUB_PUBLISH_KEY
and PUBNUB_SUBSCRIBE_KEY
with the respective publish and subscribe keys you obtained from the PubNub Admin Portal.
You can complete your app by adding the message input fields, sending chat buttons, and custom CSS to style these elements. Check out the Simple Chat GitHub for more info and the complete source code.
Demo: Chat in More than 10 Lines of Code
OK, the title of this blog is a bit gimmicky... clearly you would not release a chat application that has just 10 lines of source code.
PubNub offers many SDKs, including a dedicated Chat SDK tailored specifically to the chat rooms by offering easy-to-use methods that let you build exactly what you need, with features including:
- Group channel creation including 1:1 conversations and threads
- Typing Indicators: Indicate if users are typing messages in a channel
- Read Receipts: Enable users to track the delivery of messages in a channel
- Sending and Receiving Files: Upload and share media files with other users in the app
- Message Persistence: Store and retrieve past messages, ensuring users can access chat history after disconnecting. PubNub's Message Persistence feature allows messages to be stored in the cloud and retrieved using the History API, enabling reliable experiences.
- Online/Offline Presence Indicators: Track the online and offline status of users and devices in real time and store custom state information
- Unread Message Count: Obtain the count of messages in channels that were published after a specific timestamp
To learn more, we have a dedicated Chat SDK Demo app with source code.
We also have a dedicated Chat SDK tutorial that will get you up and running with the basics and explore more advanced features of the software development kit.
Production-ready live chat features
When building a production-ready live chat for an app or website using a real-time messaging service, key considerations include scalability, low-latency message delivery, message sanitization, and security. A robust WebSocket-based or event-driven architecture is essential for maintaining persistent, bi-directional communication. Features like presence tracking, message history storage, and typing indicators enhance UX, while end-to-end encryption and access control ensure security. Optimized SDKs for web and mobile platforms streamline integration, and offline message caching improves reliability. Chat moderation filters profanity, removes malicious scripts (XSS protection), and normalizes input to prevent injection attacks. Implementing real-time sanitization at the edge before message delivery minimizes latency and offload processing from clients. Efficient sanitization pipelines leverage regex, NLP-based filtering, and customizable rule sets to balance performance with content moderation accuracy. Additionally, serverless functions enable event-driven automation, and real-time analytics help monitor chat performance and engagement at scale.
Here are a few example use cases:
- Virtual Events: streaming chat in live events
- Telemedicine: private messaging between doctors and patients
- Gaming: live chat for online game players
- Support: chat between agents and customers
- Marketplaces: Communication between buyers and sellers
- Collaboration: team communication at the workplace
What Else Can I Do With PubNub?
PubNub maintains 15+ synchronized global points of presence that can deliver messages to any device in under 100 milliseconds. PubNub has features like Mobile Push Notifications or Functions: serverless event-driven scripts that run within PubNub’s network, allowing real-time data processing without external servers. They can modify, filter, or enrich messages in transit, trigger actions based on events, and integrate with third-party APIs
Using PubNub SDKs, developers can quickly build chat and other real-time features without sacrificing a significant amount of time learning, creating, and managing the mechanics behind sending messages or other data in real time. All of the scaling and infrastructure are handled for you. With PubNub, you can focus on the front end of your game without worrying about the infrastructure behind it.
Check out some more chat resources to get you started today:
- How to guides walking through specific use cases
- The Chat SDK tutorial will walk you through the basic and more advanced features of our SDK.
- See our full range of Chat Demos.
Have any questions or concerns? Feel free to reach out to our team at devrel@pubnub.com
See also: