Accepted answer

right, what i should do is just use cookies for your session. that way any front end ajax calls (including websocket) will use the cookie in the request headers.

with the http only setting set on the cookie, no front end javascript can modify (or access) the session cookie, but it is still used by the browser on any outgoing request.

in my opinion this is the safest way for using the session id, without the front end needing to know about the existence of the cookie in the first place.

if the session in koa doesn't exist any more, you automatically know the user is logged out as well.

i've made a little example for this (there is a github link below):

first the index.js:

'use strict';

const session = require('koa-session');
const koa = require('koa');
const websockify = require('koa-websocket');
const route = require('koa-route');

const app = websockify(koa());

app.keys = ['some secret hurr'];
const sessionstore = session(app);


app.use(route.all('/', function* (next) {
  // ignore favicon
  if (this.path === '/favicon.ico') return;

  let n = this.session.views || 0;
  this.session.views = ++n;
  yield next;
}));'/', function* (next) {
  this.websocket.on('message', (message) => {
    let n = this.session.views || 0;
    this.session.views = ++n;

    if (message === 'ping') {
      // return the amount of sessions (n) when the client sends ping
      this.websocket.send('pong ' + n);

  yield next;


console.log('listening on port 3000');

and then the index.html:

    var ws = new websocket("ws://localhost:3000/");

    ws.onopen = function() {
      // sends a message

    ws.onmessage = function(e) {
      // receives a message.

    ws.onclose = function() {

i've put all of this in to a working example on github.

Related Query

More Query from same tag