Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท Rooms and Namespaces

Socket.IO Namespaces

Learn Socket.IO namespaces. Create custom namespaces with io.of, connect clients to them, see how they share one connection, keep events and rooms isolated, and use dynamic namespaces.

Rooms group sockets inside one communication channel. Namespaces split the channel itself into separate, independent areas of your application. Think of a namespace as a separate "app within the app" with its own connection event, its own middleware, its own events and its own rooms, all running over a single physical connection.

The default namespace and custom ones

Everything so far used the default namespace, /. io.on('connection', ...) is shorthand for io.of('/').on('connection', ...). You can create others with io.of(name):

JavaScript
const chat = io.of('/chat');
const admin = io.of('/admin');

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

admin.on('connection', (socket) => {
  socket.emit('stats', { users: chat.sockets.size });
});

A client picks the namespace by adding it to the URL (read-only snippets):

JavaScript
const chatSocket = io('https://example.com/chat');
const adminSocket = io('https://example.com/admin', { auth: { token } });

The namespace is a path in the URL passed to io, but it is not the same as the path option (which is the HTTP endpoint, /socket.io/, shared by everything).

Both clients above end up with different socket objects, and each has its own id per namespace. If both are used on the same page, they share one underlying connection (multiplexing) so the browser opens one WebSocket, not two. The socket.nsp property tells you which namespace a socket belongs to.

What namespaces isolate

  • Events: chat.emit('message') never reaches admin sockets, even if they listen for message.
  • Rooms: a room named lobby in /chat is a different room from lobby in /admin.
  • Middleware: chat.use(...) applies only to /chat, so you can require stricter authentication on /admin.
  • Connection handlers: each namespace has its own connection event.

Try it: two namespaces, same room name, same event name, nothing leaks.

Node.js Two namespaces, same names, no leaks

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.

Each message stays in its namespace, even though both used the event name message and the room name lobby.

Why and when to use namespaces

Good reasons:

  • Different parts of an app with different rules: /chat for users, /admin for staff, /stats for dashboards.
  • Different authentication per area with per-namespace middleware.
  • Keeping event names from colliding between features developed by different teams.
  • Multi-tenant apps, one namespace per customer (often as a dynamic namespace).

Bad reasons: using a namespace per chat conversation or per user. Those are rooms. A namespace is meant to be created by the developer at startup, a handful of them, while rooms come and go at runtime by the thousands. The next lesson, Managing Sockets from the Server, compares them in more depth.

Connecting to a namespace that does not exist

A client that asks for a namespace the server never defined receives a connect_error with the message Invalid namespace. This is easy to hit when a typo sneaks into the URL. The stand-in reproduces it, and also shows a namespace-level middleware that rejects some clients:

Node.js Invalid namespace and namespace middleware

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.

Only the first and last attempts connect. The second fails with Invalid namespace, and the third is stopped by the /admin middleware.

Dynamic namespaces

Sometimes the set of namespaces is not known in advance, for example one per tenant (/tenant-acme, /tenant-globex). Instead of a fixed string, io.of accepts a regular expression or a function that decides whether a name is valid (read-only snippet):

JavaScript
const tenants = io.of(/^\/tenant-[a-z0-9]+$/);

tenants.on('connection', (socket) => {
  console.log('connected to', socket.nsp.name); // e.g. "/tenant-acme"
});

// A function can check a database; call next(err, allow)
io.of(async (name, auth, next) => {
  const exists = await tenantExists(name.slice(1));
  next(null, exists);
});

The server creates the namespace on the first matching connection. Be strict with the pattern and consider the cost: every namespace has its own state in memory.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a client connect to the /admin namespace?

    The namespace is the path part of the URL given to io(). The path option is the HTTP endpoint and is a different thing.
  2. 2. Two namespaces both have a room called 'lobby'. What is true?

    Rooms are scoped to the namespace in which they were created, so the names do not collide.
  3. 3. A client opens sockets to /chat and /admin on one page. How many WebSocket connections does the browser use?

    Namespaces are multiplexed over one Engine.IO connection.
  4. 4. What error does a client get for a namespace that was never defined on the server?

    The connection to that namespace is refused and connect_error reports Invalid namespace.

Summary

  • A namespace is an isolated sub-application with its own events, rooms, middleware and connection handler.
  • io.of('/name') defines it on the server; io(url + '/name') connects on the client.
  • Multiple namespaces share a single underlying connection.
  • Use a few namespaces for distinct areas or different auth rules; use rooms for dynamic groups.
  • Unknown namespaces fail with Invalid namespace; regex or function namespaces cover dynamic cases.

Next: Managing Sockets from the Server