Using middlewares on application level #3745
-
Hi mates! I try to create common middleware for my websocket application, but I can't to understand socket.io middlewares philosophy when I use namespaces. What I doing: // server side
import { Server } from 'socket.io';
const websocket = new Server();
websocket.use((socket, next) => {
console.log('common');
next();
});
websocket.of('/admin').use((socket, next) => {
console.log('admin');
next();
});
// client side
const socket = io.connect('/admin'); Expected behavior: Real behavior: I have same issue when I try to create dynamicly namespaces with regexp: // server side
import { Server } from 'socket.io';
const websocket = new Server();
websocket.use((socket, next) => {
console.log('common');
next();
});
websocket.of(/^\/\w+$/).use((socket, next) => {
console.log('regexp');
next();
});
websocket.of('/admin').use((socket, next) => {
console.log('admin');
next();
});
// client side
const socket = io.connect('/admin'); Expected behavior: Real behavior: How can I to set one middleware on all namespaces? NOTE: in this case I was use "standalone" initialization type, but I reproduced same behavior with different initialization types from official site |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This was indeed the behavior in Socket.IO v2: even when using a namespace ( This should not happen anymore with Socket.IO v3. Regarding the dynamic namespace feature, the middleware registered here: websocket.of(/^\/\w+$/).use((socket, next) => {
console.log('regexp');
next();
}); is indeed registered on each child namespace. I will update the documentation about this. |
Beta Was this translation helpful? Give feedback.
This was indeed the behavior in Socket.IO v2: even when using a namespace (
io.connect('/admin')
), you were implicitly connected to the main namespace (/
), which is quite surprising.This should not happen anymore with Socket.IO v3.
See also: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/#No-more-implicit-connection-to-the-default-namespace
Regarding the dynamic namespace feature, the middleware registered here:
is indeed registered on each child namespace. I will update the documentation about this.