Why ActionCable does not provide access to sessions?

Is it an intentional choice, for example for security reasons? Or something that can be implemented down the road?

Here’s a statement from the Rails guides about sessions and cookies.

The WebSocket server doesn’t have access to the session, but it has access to the cookies. This can be used when you need to handle authentication. You can see one way of doing that with Devise in this article.

I think part of it might be due to the fact that sessions aren’t necessarily stored in cookies - they could be stored in Redis/DB/wherever.

As websocket has long connections which can span for days and countless operations as opposed to HTTP requests which are short-lived and only result in one operation, the semantics of session storage are a lot more complex.

Unlike ActionDispatch, ActionCable has no concept of a request/response cycle. When would the session need to be refetched from the database? This is a very app-specific question that Rails really can’t provide an omakase answer for.

Additionally, unlike with HTTP (which consists of stateless requests other than cookies), sessions are a first-class concept with WebSockets. In ActionCable, instance variables in channels and connections survive for the entire duration of the WebSockets connection. Unlike with HTTP, there is no need to have an external store to hold session data (Rails’s session is a way to give state to the inherintly stateless protocol for HTTP, there is no such need with WebSockets)

Signed cookies provide a really good answer for authn. Origin header checks provide CSRF protection. Instance variables provide storage for session data.

1 Like

@benaubin, thank you for the very detailed answer!