Skip to main content
Version: 4.x

Integrating Socket.IO

Socket.IO is composed of two parts:

  • A server that integrates with (or mounts on) the Node.JS HTTP Server (the package)
  • A client library that loads on the browser side (the package)

During development, serves the client automatically for us, as we’ll see, so for now we only have to install one module:

npm install

That will install the module and add the dependency to package.json. Now let’s edit index.js to add it:

const express = require('express');
const { createServer } = require('node:http');
const { join } = require('node:path');
const { Server } = require('');

const app = express();
const server = createServer(app);
const io = new Server(server);

app.get('/', (req, res) => {
res.sendFile(join(__dirname, 'index.html'));

io.on('connection', (socket) => {
console.log('a user connected');

server.listen(3000, () => {
console.log('server running at http://localhost:3000');

Notice that I initialize a new instance of by passing the server (the HTTP server) object. Then I listen on the connection event for incoming sockets and log it to the console.

Now in index.html add the following snippet before the </body> (end body tag):

<script src="/"></script>
const socket = io();

That’s all it takes to load the, which exposes an io global (and the endpoint GET /, and then connect.

If you would like to use the local version of the client-side JS file, you can find it at node_modules/


You can also use a CDN instead of the local files (e.g. <script src=""></script>).

Notice that I’m not specifying any URL when I call io(), since it defaults to trying to connect to the host that serves the page.


If you're behind a reverse proxy such as apache or nginx please take a look at the documentation for it.

If you're hosting your app in a folder that is not the root of your website (e.g., then you also need to specify the path in both the server and the client.

If you now restart the process (by hitting Control+C and running node index.js again) and then refresh the webpage you should see the console print “a user connected”.

Try opening several tabs, and you’ll see several messages.

A console displaying several messages, indicating that some users have connected

Each socket also fires a special disconnect event:

io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');

Then if you refresh a tab several times you can see it in action.

A console displaying several messages, indicating that some users have connected and disconnected

You can run this example directly in your browser on: