Node.js
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.
Exercise 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.
Show example solution
const socketIo = require("socket.io");
const io = socketIo();
const adminIo = io.of("/admin");
adminIo.on("connection", (socket) => { console.log("Admin"); });
console.log("namespaces ready");
Test yourself
-
Complete the io.of call
const adminIo = io.of("____");
Show answer
const adminIo = io.of("/admin");
-
Match each piece to its role
- io.of
- Creates a namespace
- /admin
- Namespace path
- adminIo.on
- Listens in that channel
- /
- Default namespace
-
What does io.of('/admin') create?
io.of("/admin")
- A new port
- A new room
- A new namespace
- A new client
Show answer
A new namespace — io.of creates a new namespace.
Next lesson: Summary - Realtime