Learn to Code via Tutorials on Repl.it!

← Back to all posts
✉ TUTORIAL | HOW TO BUILD A CHAT APP ✉
h
zplusfour (832)

Hi, this is a tutorial about how to build a chat app

here is it @Leroy01010

Let's start


1. Libraries

We need socket.io to make a connection from user to a user.
And we need an express server, and also http.

Code:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

2. Socket.io connection

We need some lines of code, to make a websocket connection.

The first block of code is for the username (for the chat app) and then to send: 'Username joined the chat...'

The second block of code is the opposite of the first one.

The third block of code is about the message, when the user sends a message, it will send his message with the username and the date of the message.

The fourth code block (outside of the websocket connection) is the port listen handler.
Code:

io.sockets.on('connection', (socket) => {
  socket.on('username', function(username) {
    socket.username = username;
    io.emit('is_online', '🔵 <i>' + socket.username + ' joined the chat..</i>');
  });

  socket.on('disconnect', (username) => {
    io.emit('is_online', '🔴 <i>' + socket.username + ' lefted the chat..</i>');
  });

  socket.on('chat_message', (message) => {
    let time = new Date();
    io.emit('chat_message',`<i>${time.toLocaleTimeString()}</i><br>` +  '<strong>' + socket.username + '</strong>: ' + message);
  });
});

// Server listen handler
server.listen(8080, ()=>{
    console.log('Connected!');
});

4. Render the HTML file for the chat.

We need to add some lines before the socket connection.
To render the HTML chat app file.

Code:

app.get('/', function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

5. Fill the index.html with code to make a chat app.

We need to use jQuery to make a form for the chat.

Code:

<!DOCTYPE html>
<html>
  <head>
    <title>Chatorzo</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font: 13px Helvetica, Arial; }
        form { background: #fff; padding: 3px; position: fixed; bottom: 0; width: 100%; border-color: #000; border-top-style: solid; border-top-width: 1px;}
        form input { border-style: solid; border-width: 1px; padding: 10px; width: 85%; margin-right: .5%; }
        form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; margin-left: 2%; }
        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages li { padding: 5px 10px; }
        #messages li:nth-child(odd) { background: #eee; }
    </style>
    <script src="../../socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  </head>
  <body style="background: grey;">
      <header align="center">
          <h1>Chatorzo</h1>
      </header>
      <br>
      <br>
      <br>
    <ul id="messages"></ul>
    <form action="/" method="POST" id="chatForm">
      <input id="txt" autocomplete="off" autofocus="on" placeholder="Your message" /><button>Send</button>
    </form>
    <script>
            var socket = io.connect('https://chatorzo-2.zdev1.repl.co');
            $('form').submit(function(e){
                e.preventDefault();
                socket.emit('chat_message', $('#txt').val());
                $('#txt').val('');
                return false;
            });
            socket.on('chat_message', function(msg){
                $('#messages').append($('<li>').html(msg));
            });
            socket.on('is_online', function(username) {
                $('#messages').append($('<li>').html(username));
            });
            var username = prompt('Username:');
            socket.emit('username', username);
    </script>
  </body>
</html>

So we basically added some CSS and some javascript (jQuery) to:

  • Make it responsive and beautiful.
  • Connect the socket code to the HTML file.

And that's it

Have a great day!

Source code: https://repl.it/@ZDev1/chatorzo-2

Commentshotnewtop
Muhammad_SJC (92)

That is a great chat app. But I have found a tool called Google Firebase that actually handles all the backend database for you. Check out the chatting app I made with Firebase: https://repl.it/talk/share/Chat-App-Using-Firebase-Realtime-Database/55382

If you want a tutorial on how to make this, then please upvote!

zplusfour (832)

@Muhammad_SJC this is cool!
nice chat!
I know what is firebase, I'll learn it
but tell me, why did you make the username as a javascript prompt?
you can do a google auth with firebase!

Muhammad_SJC (92)

@ZDev1 I know and I am working on it, but this is just a prototype

moradz (1)

Well done zohdi
You are awesome

nngggaming (0)

Kind of good and bad... good: it’s a wonderful chat app. Bad: it is connected through all repls? I followed all the steps above, and sent some messages, at the same time opened up another tab with your repl and yeah saw the messages i sent...

Is there any way to make it more private(like only people with my repl project link can see the messages)?

zplusfour (832)

@nngggaming I have used Socket.IO
which it let's you to connect users to other users.
It is not a database, messages aren't saved in the database, only if someone joined the repl (if one of your family or friends or people on repl.it) can see messages on this web.

M4urice (0)

This may be a stupid question but I'm rather new to coding and I'm unsure of where to place the code for rendering the HTMl

zplusfour (832)

@M4urice it is fine
first, just make a HTML file (index.html)
And this block of code, renders the html file:

app.get('/', function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

And then you'll be ready :)

M4urice (0)

Thanks for the help @ZDev1

ColeBosman (11)

It says .io isnt defined.

ColeBosman (11)

@ZDev1 Do you know any potential fixes?

oignons (314)

It's XSS-vulnerable.

Highwayman (1442)

I feel...so lost.... :(

I can’t understand the html stuff very well without any explanations or breaking down.

zplusfour (832)

@Highwayman oh sorry
I'll explain to you:
in the HTML file, we did:

  • Styling to make it colorful (not a lot)
  • And then I wrote then socket.io cdn for the chat, and a jQuery cdn
  • And then this <ul> is the messages container
    When someone sends a message it will append in it as a <li> element
  • And the form is where you need to write your message
  • And the script tag, I wrote in it some code to:
  1. connect the websocket to the website
  2. make a little bit jQuery code to submit the form when you send a message
  3. and some append things (I explained in this comment)
    and then the username, it will be as a javascript prompt!

And that's it!

Highwayman (1442)

Wow thank you, very succinct! The ul thing is neat :)
@ZDev1

retronbv (103)

lefted the chat.

left* the chat

Also when trying to send message

Cannot POST /

retronbv (103)

@ZDev1 Cannot POST / when trying to send msg

zplusfour (832)

@retronbv ok ok, I AM TRYING TO FIX THIS

retronbv (103)

@ZDev1 SHEESH OK IM JUST TRYING TO GIVE YOU ALL THE ERRORS I FOUND

Highwayman (1442)

@retronbv
@ZDev1
Lol this convo is literally me and my best friend during any game.

ZenoxHosting (9)

ReferenceError: Server is not defined

any fix?

EpicGamer007 (1282)

Also, the repl in the link, it doesn't work:

EpicGamer007 (1282)

@CodeLongAndPros , im on school comp, i cant download extensions :(

AstOwOlfo (245)

How is it related to repl? That’s the default ejs error page. It’s actually @ZDev1 who is responsible for the light theme @CodeLongAndPros

zplusfour (832)

@agent9002 he means that he isn't using an extension that makes every website (error page is a website) has a dark theme

CodeLongAndPros (1538)

@ZDev1 No, the Console is light theme, which sucks.

EpicGamer007 (1282)

@ZDev1 , since when did md suck?

zplusfour (832)

@EpicGamer007 md sucks when you're trying to do ascii

EpicGamer007 (1282)

Wow! This is really cool! More node tuts plez! I definetly wanna try this.

zplusfour (832)

@Leroy01010 thanks!
Learn it and submit your mission to your teacher!