Coder Social home page Coder Social logo

Comments (8)

albertogasparin avatar albertogasparin commented on May 14, 2024 6

Well, I've made it work in this way:

import http from 'http';
import socketIO from 'socket.io';
import koa from 'koa';
import session from 'koa-session';

// your koa setup
const app = new koa();
app.keys = ['my-secret'];
app.use(session({}, app));

// socket.io binding
app.server = http.createServer(app.callback());
app.io = socketIO(app.server);

// socket.io middleware to set socket.session
app.io.use(function (socket, next) {
  let error = null;
  try {
    // we manually create a koa context, so we can use it to retrieve the session
    let context = app.createContext(socket.request, socket.response);
    socket.session = context.session;
  } catch (err) {
    error = err;
  }
  return next(error);
});

In this implementation, the main difference with cxt.session is that socket.session is "static": it is not a getter but it is just the returned value (something to not worry about with cookies).

from session.

thanhlq avatar thanhlq commented on May 14, 2024 1

it does NOT work (ctx.session is undefined) if I configure a session store e.g.

(Knowing that, the session store is working fine with my Rest API)

sessionConfig.store = new SessionStoreImpl(); // redis
app.use(session(sessionConfig, app));

Thanks very much for any ideas?

from session.

lastHelp avatar lastHelp commented on May 14, 2024 1

@thanhlq
I've found a way to fix this.
here is some code:

app.io.use(async function (socket, next) { // making io middleware async, not sure it's good idea
// ... 
try {
// ...
 const ctx = app.createContext(socket.request, new http.OutgoingMessage())
// calling initFromExternal to fetch session data from external store, if you are using other than koa-session module you have to find how to do this. 
 await ctx.session._sessCtx.initFromExternal()
 // now ctx.session is full of data
}
// ...
})

from session.

 avatar commented on May 14, 2024 1

Hi everyone!

Just wanted to build on the various solutions presented here to offer something that is almost equivalent to the official documentation for integrating express-session into socket.io as seen here. Idea is to just re-use the existing session middleware to populate the newly created context and to attach the session to "socket.request". Currently unsure about whether using async'ed socket.io middleware is supported or not, the docs are a bit unclear.

import http from 'http';
import socketIO from 'socket.io';
import koa from 'koa';
import session from 'koa-session';

// your koa setup
const app = new koa();
app.keys = ['my-secret'];

const sessionMiddleware = session({}, app);
app.use(sessionMiddleware);

// socket.io binding
app.server = http.createServer(app.callback());
app.io = socketIO(app.server);

// socket.io middleware to set socket.session
app.io.use(function (socket, next) {
  let error = null;
  try {
    // we manually create a koa context, so we can use it to retrieve the session
    let context = app.createContext(socket.request, socket.response);
    await sessionMiddleware(context, next);
    socket.request.session = context.session;
  } catch (err) {
    error = err;
  }
  return next(error);
});

from session.

hedgerh avatar hedgerh commented on May 14, 2024

@Gacnt - Did you have any luck figuring this out? I'm trying to figure out the best way to use session storage when using the ws websocket library.

from session.

marceloch2 avatar marceloch2 commented on May 14, 2024

This is not working for me, TypeError: Cannot read property 'url' of undefined, some idea?

from session.

epszaw avatar epszaw commented on May 14, 2024

@albertogasparin it's working! Thank you, mate, i lost a lot of time before found your solution! ❤️

from session.

ejose19 avatar ejose19 commented on May 14, 2024

@lastHelp Your solution works great, all other "workarounds" involves too much hacking to get the session, but using .initFromExternal reuses everything already configured.

One note regarding types, I had to change new http.OutgoingMessage() to new http.ServerResponse(socket.request) or you will get "Argument of type 'OutgoingMessage' is not assignable to parameter of type 'ServerResponse'."

from session.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.