Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 36 ยท Getting Started

Your First Socket.IO Server and Client

Install Socket.IO, create a server with Node's http module or Express, connect a browser client, send your first events, and see how the stand-in mirrors the real API step by step.

Time to build something. In this lesson you will install Socket.IO, write a small server, connect a client, and exchange a greeting in both directions. The real commands and files are shown read-only; every idea is then reproduced on the runnable stand-in so you can change the code and watch what happens.

Install

You need Node.js 18 or newer. In a new folder:

Terminal
npm init -y
npm install socket.io

The server package is socket.io. The browser and Node client package is socket.io-client; in a browser page you can also load a script that the server serves for you at /socket.io/socket.io.js, so installing the client package is optional for simple pages.

Use ES modules by adding "type": "module" to package.json, or use require in CommonJS files. This course uses import.

The smallest server

The shortest possible server listens on its own port:

JavaScript
// server.js
import { Server } from 'socket.io';

const io = new Server(3000, {
  cors: { origin: 'http://localhost:5173' }, // allow your front-end origin
});

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

  socket.emit('welcome', 'Hello from the server!');

  socket.on('thanks', (name) => {
    console.log(`${name} says thanks`);
  });

  socket.on('disconnect', (reason) => {
    console.log('client left:', reason);
  });
});

Four things happen here:

  1. new Server(3000, options) creates an io object and starts listening.
  2. io.on('connection', handler) runs once for every new client. The socket argument represents that one client's connection.
  3. socket.emit(name, ...args) sends an event to that one client.
  4. socket.on(name, handler) listens for events from that client. The special names disconnect and connect_error are reserved for lifecycle events.

The matching client

In a browser page served from any origin:

HTML
<script src="https://cdn.socket.io/4.8.1/socket.io.min.js"></script>
<script>
  const socket = io('http://localhost:3000');

  socket.on('connect', () => {
    console.log('connected as', socket.id);
  });

  socket.on('welcome', (message) => {
    console.log(message);
    socket.emit('thanks', 'Ana');
  });
</script>

With a bundler you write import { io } from 'socket.io-client' instead. When the page is served by the same host and port as the Socket.IO server, you can call io() with no arguments and it connects to the page's own origin.

The connect event fires on the client each time the connection is (re)established. socket.id is a fresh random identifier per connection, so it changes after a reconnect. Do not treat it as a user id.

Run the same flow on the stand-in

The program below follows the same four steps. Server and connect come from the labelled stand-in at the bottom (it is in-process, with no network). The code on top is shaped like the real thing, so porting it later is mostly a matter of replacing the import.

Node.js Welcome and thanks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The order of the log lines is the real order of events: the server sees the connection, the client sees connect, then the welcome message, the thanks, and finally the disconnect with the reason client namespace disconnect.

Attaching to an existing HTTP server

Real applications rarely have a bare Socket.IO server. They already serve pages and an API, so you attach Socket.IO to the same HTTP server and share one port.

With Node's own http module:

JavaScript
import { createServer } from 'node:http';
import { Server } from 'socket.io';

const httpServer = createServer((req, res) => {
  res.end('Plain HTTP still works');
});
const io = new Server(httpServer);

httpServer.listen(3000);

With Express (the app is only a request handler for createServer):

JavaScript
import express from 'express';
import { createServer } from 'node:http';
import { Server } from 'socket.io';

const app = express();
app.use(express.static('public')); // index.html, client.js ...

const httpServer = createServer(app);
const io = new Server(httpServer);

io.on('connection', (socket) => {
  socket.on('chat message', (msg) => io.emit('chat message', msg));
});

httpServer.listen(3000, () => console.log('http://localhost:3000'));

Common mistake: calling app.listen() instead of httpServer.listen(). app.listen creates a new HTTP server internally, so the one Socket.IO is attached to never receives any traffic.

Socket.IO answers on the path /socket.io/ by default. Change it with the path option on both sides if that path collides with something else (new Server(httpServer, { path: '/live/' }) and io(url, { path: '/live/' })).

Several clients and per-socket state

Each browser tab is its own socket. The connection handler runs separately for each, and variables you declare inside it belong to that one connection. That is a clean place to keep per-client state:

Node.js Per-connection state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

a ends with two clicks and b with one, because clicks is a separate variable per connection. The counter online lives outside the handler, so it is shared by everyone.

Per-connection variables vanish when the socket disconnects, and a reconnect creates a new socket with fresh state. Store anything that must survive (scores, carts, messages) in a database keyed by a user id, not in a closure.

Troubleshooting checklist

  • "CORS error" in the browser console. The client page and the server have different origins. Add cors: { origin: '...' } to the server options.
  • Client keeps trying and never connects. Check the URL, port, and path; check that the server process is running.
  • Nothing logs on the server with Express. You probably called app.listen.
  • Version mismatch. Keep server and client on the same major version (this course uses v4).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which line makes the server react every time a new client connects?

    The connection event is emitted on the io object, and the handler receives the new client's socket.
  2. 2. You attach Socket.IO to an Express app. Which call starts the server correctly?

    app.listen creates a different HTTP server. Socket.IO must be attached to the server you actually listen on.
  3. 3. A variable declared inside the connection handler is...

    Each connection runs the handler separately, so closure variables are per socket; a reconnect gives a new socket.
  4. 4. Why is socket.id a poor user identifier?

    A new id is assigned each time the connection is established, so use a real user id from authentication.

Summary

  • Install socket.io for the server and socket.io-client (or the served script) for clients.
  • io.on('connection', socket => ...) runs once per client; socket.emit and socket.on send and receive events for that client.
  • Attach Socket.IO to an http.Server and call listen on that server, not on the Express app.
  • Per-connection variables live in the handler's closure; durable data belongs in a database.
  • Use the cors and path options when origins or URLs differ.

Next: Serving the Client, CORS and Options