メインコンテンツへスキップ

グローバルミドルウェアを登録する方法

Socket.IO v2 で、メインの名前空間に登録されたミドルウェアは、クライアントが最初にメインの名前空間に接続してからカスタムの名前空間に接続するため、全名前空間に適用されるグローバルミドルウェアとして機能します

// Socket.IO v2

io.use((socket, next) => {
// always triggered, even if the client tries to reach the custom namespace
next();
});

io.of("/my-custom-namespace").use((socket, next) => {
// triggered after the global middleware
next();
});

これは Socket.IO v3 以降では当てはまりません。メインの名前空間に関連付けられたミドルウェアは、クライアントがメインの名前空間に接続しようとしたときにのみ呼び出されます

// Socket.IO v3 and above

io.use((socket, next) => {
// only triggered when the client tries to reach the main namespace
next();
});

io.of("/my-custom-namespace").use((socket, next) => {
// only triggered when the client tries to reach this custom namespace
next();
});

新しいバージョンでグローバルミドルウェアを作成するには、ミドルウェアをすべての名前に空間に関連付ける必要があります

  • 手動で行うか
const myGlobalMiddleware = (socket, next) => {
next();
}

io.use(myGlobalMiddleware);
io.of("/my-custom-namespace").use(myGlobalMiddleware);
  • new_namespace イベントを使用して
const myGlobalMiddleware = (socket, next) => {
next();
}

io.use(myGlobalMiddleware);

io.on("new_namespace", (namespace) => {
namespace.use(myGlobalMiddleware);
});

// and then declare the namespaces
io.of("/my-custom-namespace");
注意

new_namespace リスナーの前に登録された名前空間は影響を受けません。

  • または、動的な名前空間を使用する場合は、親の名前空間にミドルウェアを登録することで
const myGlobalMiddleware = (socket, next) => {
next();
}

io.use(myGlobalMiddleware);

const parentNamespace = io.of(/^\/dynamic-\d+$/);

parentNamespace.use(myGlobalMiddleware);
注意

既存の名前空間は、常に動的な名前空間に優先します。たとえば、

io.of("/admin");

io.of(/.*/).use((socket, next) => {
// won't be called for the main namespace nor for the "/admin" namespace
next();
});

関連