CodeBlanks Logo Icon CodeBlanks

Namespaces

Learn namespaces with Socket.io namespaces.

Namespaces

A namespace creates separate communication channels on a single Socket.io server. You create a new namespace with io.of("/path"). Each namespace manages its own connections and events, so you can run multiple independent channels on one port.

Example: const adminIo = io.of("/admin"); adminIo.on("connection", (socket) => { console.log("Admin connected"); });. The /admin namespace is a separate channel; the client connects to the /admin path. The default namespace is /. Namespaces are used in multi-tenant apps, for channel separation by role, and in modular architectures. A room groups clients inside a channel; a namespace separates the channel itself.

Using a namespace

After creating a namespace you use it just like io. You listen to connections with adminIo.on("connection", ...) and broadcast with adminIo.emit(...). Each namespace has its own rooms and events.

Example: const adminIo = io.of("/admin"); adminIo.on("connection", (socket) => { adminIo.emit("message", "Admin arrived"); });. Every client that connects to the /admin namespace receives the message event. On the client side you connect with io("/admin"). Events do not mix between namespaces; /admin and /user are separate channels. This is ideal for separating flows by role.

Practice Create an admin namespace

Use the io object below. Create the admin namespace with const adminIo = io.of("/admin"). Define adminIo.on("connection", (socket) => { console.log("Admin"); }). Print "namespaces ready" with console.log.

Starter code

index.js
const socketIo = require("socket.io");
const io = socketIo();

// Create the "/admin" namespace and listen to connection
// write here

// Print "namespaces ready"
// write here

Sample solution

index.js
const socketIo = require("socket.io");
const io = socketIo();
const adminIo = io.of("/admin");
adminIo.on("connection", (socket) => { console.log("Admin"); });
console.log("namespaces ready");

Expected output

namespaces ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the io.of call

Question
const adminIo = io.of("____");
Answer
const adminIo = io.of("/admin");

Explanation: io.of('/admin') creates the admin namespace.

2 Match each piece to its role

Term Meaning
io.of Creates a namespace
/admin Namespace path
adminIo.on Listens in that channel
/ Default namespace

3 What does io.of('/admin') create?

index.js
io.of("/admin")
  • A new port
  • A new room
  • A new namespace Correct answer
  • A new client

Explanation: io.of creates a new namespace.

All lessons in Advanced