Build a Chat Application in JavaScript in 10 Lines of Code
Published: 2024-01-26 18:13:32

[PubNub Chat](https://www.pubnub.com/solutions/chat/) offers a robust real-time network and APIs to send and receive data in any application. Take advantage of our services to quickly build chat with enterprise-grade security, scalability, and reliability. PubNub eliminates the time it takes to set up and manage your infrastructure so you can focus on solving business problems for your customers.

Follow this tutorial to learn how to create a live chat app with only ten lines of code using the [PubNub JavaScript SDK](https://www.pubnub.com/docs/sdks/javascript/).

**Try the Chat Demo**
---------------------

There are two methods available for you to try out this demo:

1.  Our [interactive 10-chat demo](https://www.pubnub.com/demos/10-line-chat/) will take you through this mini-chat application step-by-step. This demo is the same code you can copy below with an interactive walkthrough.
    
2.  Clone the [GitHub repository](https://github.com/PubNubDevelopers/JavaScript-Simple-Chat) to see how the application works behind the scenes and build your own features.
    

Open the demo in two tabs to chat between windows!

![Chat in 10 lines of JavaScript](/cdn/3prze68gbwl1/1BrNYTZ7F0JKsuywM46pTz/01b9c8c3eeaa484e37b7729f2e40edaa/10-chat-screenshot.png)

**How to Build Your Own Real-Time Chat App**
--------------------------------------------

To start your real-time chat app, you'll need to obtain the API keys necessary to connect ot the PubNub platform: the publish and subscribe keys. You can get your own set of free API keys by following these steps:

1.  Log in to the [Admin Portal](https://admin.pubnub.com/).
    
2.  Click on the Apps tab on the left-hand side.
    
3.  Click on the “Create New App” button to create a new application. Give the application a name and click the “Create” button. 
    
4.  Click on your newly created app. You will be brought to the keysets page for this application. Note that each application created automatically generates a new keyset for you, but you will be creating a new keyset to enable specific features.
    
5.  Click the “Create New Keyset” button on the upper right side of the portal.
    
6.  A pop-up appears. Give the keyset a name and click the “Create” button.
    
7.  Click on the newly created keyset.
    
8.  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.

```js
https://cdn.pubnub.com/sdk/javascript/pubnub.7.5.0.js
https://cdn.pubnub.com/sdk/javascript/pubnub.7.5.0.min.js
```

Then, configure PubNub by adding the following code to the file for your application.

```js
// Open 2 tabs to chat between windows
        
// Get your PubNub keys from admin.pubnub.com
var pubnub = new PubNub(
  {publishKey: 'PUBNUB_PUBLISH_KEY', subscribeKey: 'PUBNUB_SUBSCRIBE_KEY', 
   userId: 'user1'});
var channel = '10chat';

// Add a listener to a channel and subscribe to it
pubnub.addListener({
  message: function (m) {
    box.innerHTML += newRow(m.message, 
     m.publisher);
  }
});
pubnub.subscribe({channels: [channel]}); 
// Publish new message when enter is pressed. 
input.addEventListener('keypress', function (e) {
  (e.keyCode || e.charCode) === 13 && 
   pubnub.publish({ 
    channel: channel, message: input.value, 
     x: (input.value = '')
  });
});
```

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 chat application by adding the message input fields, sending chat buttons, and custom CSS to style these elements. Check out the [Simple Chat GitHub](https://github.com/PubNubDevelopers/JavaScript-Simple-Chat) for more info and the complete source code.

What Tools Can Help Me Build Chat?
----------------------------------

[PubNub offers many SDKs](https://www.pubnub.com/docs/sdks), including a dedicated [Chat SDK](https://www.pubnub.com/docs/chat/chat-sdk/overview) tailored specifically to the chat use case by offering easy-to-user methods that let you do exactly what you want.

These SDKs make it simple to add chat to your applications. You can focus on creating the best client-side user experience while PubNub takes care of the application's server side.

Create 1:1 private chat rooms, group chats, or even mega chats for large-scale events. Here are a few examples:

-   [Virtual Events](https://www.pubnub.com/solutions/sports-media/): Streaming chat in live events
    
-   [Telemedicine](https://www.pubnub.com/solutions/digital-health/): Private chat between doctors and patients
    
-   [Gaming](https://www.pubnub.com/solutions/gaming/): Live chat for online game players
    
-   [Support](https://www.pubnub.com/solutions/communications/): Chat between agents and customers
    
-   [Marketplaces](https://www.pubnub.com/solutions/ecommerce/): Chat between buyers and sellers
    
-   [Collaboration](https://www.pubnub.com/solutions/multiuser-collaboration/): Chat for team communication at the workplace
    

Advanced Chat Features
----------------------

Once you’re sending and receiving messages, you can use PubNub Chat to build features into your chat like these:

-   [Typing Indicators](https://www.pubnub.com/docs/chat/sdks/messages/typing): Indicate if users are typing messages in a channel.
    
-   [Read Receipts](https://www.pubnub.com/docs/chat/sdks/messages/message-receipts): Enable users to track the delivery of messages in a channel.
    
-   [Sending and Receiving Files](https://www.pubnub.com/docs/chat/sdks/messages/files): Upload and share files with other users in the application
    
-   [Message Persistence](https://www.pubnub.com/docs/chat/sdks/messages/message-history): Store and retrieve messages as they get sent over the network.
    
-   [Online/Offline Presence Indicators](https://www.pubnub.com/docs/chat/sdks/users/presence): Track the online and offline status of users and devices in real time and store custom state information
    
-   [Unread Message Count](https://www.pubnub.com/docs/chat/sdks/messages/unread-counts): Obtain the count of messages in channels that were published after a specific timestamp.
    

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 [Functions](https://www.pubnub.com/products/functions/) and [Mobile Push Notifications](https://www.pubnub.com/docs/chat/sdks/push-notifications) that you can take advantage of in your product.

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 chat 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](https://www.pubnub.com/how-to/?sortBy=Most%20recent&categories=Chat) in implementing specific use cases for your chat application.
    
-   [Develop](https://www.pubnub.com/tutorials/javascript-sdk-chat-app/) an in-app chat application using the PubNub JavaScript SDK.
    
-   [Learn](https://www.pubnub.com/tutorials/chat-sdk/) how to set up and use PubNub's Chat SDK to build a flexible chat application.
    

Have any questions or concerns? Feel free to reach out to our team at [devrel@pubnub.com](devrel@pubnub.com).

How can PubNub help you?
========================

This article was originally published on [PubNub.com](https://www.pubnub.com/blog/realtime-live-chat-application-javascript-pubnub-10-lines-of-code/)

Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.

The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.

Experience PubNub
-----------------

Check out [Live Tour](https://www.pubnub.com/tour/introduction/) to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup
---------

Sign up for a [PubNub account](https://admin.pubnub.com/signup/) for immediate access to PubNub keys for free

Get Started
-----------

The [PubNub docs](https://www.pubnub.com/docs) will get you up and running, regardless of your use case or [SDK](https://www.pubnub.com/docs)