Quick introduction to WebSockets with Node.js

Created July 23, 2022


WebSockets allow you to send and receive data over a network without having to use a traditional HTTP protocol. Using WebSockets, you can build a real-time application. For example, you can send messages to other users without having to refresh the page to see the new messages.

We will be using the ws library. It is a Node.js module that allows you to create WebSockets servers and clients.


Before you get started, make sure you have Node.js installed:


In order to install the ws library you need to run the following command:

npm install ws

Next, create a new file called server.js and open it in your favorite text editor.

Creating a WebSocket server

In the server.js file, create the following code:

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    ws.onerror = function () {
        console.log("Some Error occurred");

Rundown of the code:

That way we will simulate a streaming application where the server sends a message to the client every second.

Then to start the server, run the following command:

node server.js

Next, leave the server running and open a new terminal window where we will prepare our client.

Creating a WebSocket client

In a new file called client.js file, add the following code:

const WebSocket = require('ws')
const ws = new WebSocket('ws://localhost:8081')
ws.on('open', function open() {
    ws.on('message', function message(data) {

The above code creates a new WebSocket client and connects to the server on port 8081.

When a message is received from the server, the message event is emitted.

To test the client, run the following command:

node client.js

You should see the following output:

hello world
hello world
hello world


node ws example gif


This is a simple example of how to use WebSockets with Node.js.

If you want to learn more about WebSockets, check out the official documentation.

If you want to see how WebSockets work with Laravel, check out the following tutorial:

Laravel WebSockets

For further reading, I could also suggest taking a look at the following tutorial on what the difference between SSE and WebSockets is:

SSE vs WebSockets