
Sharing Koa session with Socket.io
On real-time web apps, you might have a mixture of standard Rest API calls and Websockets calls. So, being able to retrieve the cookie session on both sides is handy, especially if you want to handle authentication.
The code I’m going to show you requires: Koa 2.x, Koa-session 5.x and Socket.io 2.x
The important bit is the Socket.io middleware. Basically we use Koa createContext method to create a Koa context from the (web)socket request, instead of from an http request.
By doing that, we are able to provide the cookie attached to the (web)socket request directly to the Koa-session middleware. That middleware extends the context with a session getter, allowing us to retrieve its value and store it in the Socket.io socket object.
The main difference between this implementation and the ctx.session call in a Koa middleware is that socket.session is static, while the former is re-evaluated every time.
