Real-time Chat Blog

Build a Chat Application in JavaScript in 10 Lines of Code

4 min read Chandler Mayo on Dec 29, 2022
Try PubNub Today

Free up to 1MM monthly messages. No credit card required.

Subscribe to our newsletter

By submitting this form, you are agreeing to our Terms and Conditions and Privacy Policy.

Learn the basics of building chat with this simple JavaScript developer tutorial.

PubNub 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.

Try the Chat Demo

There are two ways to try this demo:

- Our interactive 10-chat demo 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.

- Or you can preview a simple version of this web application right in this post:

Enter Chat Message:

Chat Output:

Open the demo in multiple windows to simulate multiple users sending and receiving messages in real time.

How to Build Your Own Real-Time Chat App

  1. Start by copying and pasting the following code into your favorite code or text editor. Save the file with the name index.html and make sure it’s saved as plain text (or doctype HTML):

    // Enter Chat and press enter
    <div><input id=input placeholder="message" /></div>
    
    // Chat Output
    <div id=box></div>
    
    <script src="https://cdn.pubnub.com/sdk/javascript/pubnub.7.2.1.min.js"></script>
    <script> (function() {
            var pubnub = new PubNub({
                publishKey: 'YOUR_PUBLISH_KEY_HERE',
                subscribeKey: 'YOUR_SUBSCRIBE_KEY_HERE'
            });
            function $(id) {
                return document.getElementById(id);
            }
            var box = $('box'),
                input = $('input'),
                channel = 'tenchatdemo';
            pubnub.addListener({
                message: function(obj) {
                    box.innerHTML = ('' + obj.message).replace(/[<>]/g, '') + '<br>' + box.innerHTML
                }
            });
            pubnub.subscribe({
                channels: [channel]
            });
            input.addEventListener('keyup', function(e) {
                if ((e.keyCode || e.charCode) === 13) {
                    pubnub.publish({
                        channel: channel,
                        message: input.value,
                        x: (input.value = '')
                    });
                }
            });
        })();
    </script>

  2. Sign in (or create an account) to the PubNub Dashboard and create a new API key set. You can create an account for free.

  3. Sign in to your PubNub Dashboard. Go to Keysets using the left-hand side navigation.

  4. Click the “Create New Keyset” button on the upper right-hand side of the portal.

  5. A pop-up appears. Give the keyset a name and click the “Create” button.

  6. Click on the newly created keyset.

  7. Copy the Publish key by clicking on the copy icon, and in the code above, replace the placeholder Publish key with the key you copied from your account.

  8. Copy the Subscribe key by clicking on the copy icon, and in the code above, replace the placeholder Subscribe key with the key you copied from your account.

  9. Save the file. Open the index.html file in a web browser. There are no other dependencies - you’re ready to demo.

  10. Type a new message and press enter to send messages. New messages will append in the messages div.

  11. Open the file in multiple tabs to simulate multiple users. 

  12. You can create a CSS file and express your look by customizing the message input and display areas.

  13. Check the Simple Chat GitHub for more info and the complete source code.

What tools can help me build chat?

PubNub offers many SDKs for all the most common languages and platforms, so it's super easy to build with our publish/subscribe messaging API built on a global network. PubNub has multiple points of presence on every inhabited continent and has many features you’ll need in any chat application use case.

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: Streaming chat in live events

  • Telemedicine: Private chat between doctors and patients

  • Gaming: Live chat for online game players

  • Support: Chat between agents and customers

  • Marketplaces: Chat between buyers and sellers

  • Collaboration: Chat for team communication at the workplace

PubNub also offers chat components for iOS, Android, React, and React Native for easy web development and mobile development. With PubNub Chat Components, you can build chat in a way that’s customized perfectly for your needs. PubNub Components are a great starting point to make chat that you can customize to your requirements. There isn’t any one size fits all Chat Components solution, but PubNub Chat Components offer the most popular chat functionality we have seen developers implement.

More Chat Features

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

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 and 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 is handled for you. With PubNub, you can focus on the front-end of your game without worrying about the infrastructure behind it. No back-end is required.

Want more help building apps with PubNub? Reach out to our team of experts.

More from PubNub

NPP and HIPAA: Notice of Privacy Practices Definition
Healthcare CategoryJan 6, 20235 min read

NPP and HIPAA: Notice of Privacy Practices Definition

A Notice of Privacy Practices (NPP) is one of the requirements of HIPAA and helps patients understand their personal data rights.

Michael Carroll

Michael Carroll

HIPAA Violation Examples
Healthcare CategoryJan 5, 20236 min read

HIPAA Violation Examples

HIPAA violations can be financially expensive and devastating to a brand. Examine some examples of HIPAA violations, and learn...

Michael Carroll

Michael Carroll

HIPAA Technical Safeguards: How To Protect Sensitive Data
Healthcare CategoryJan 5, 20236 min read

HIPAA Technical Safeguards: How To Protect Sensitive Data

HIPAA covered entities must follow the five technical safeguards to achieve HIPAA compliance and prevent data corruption.

Michael Carroll

Michael Carroll