Photo by Jade Wulfraat

Sharing Koa session with Socket.io

Alberto Gasparin
Jul 27, 2017 · 1 min read

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade