Automatically join/subscribe to a Channel when Socket connects?

Is there a way to automatically join a Phoenix Channel when a client connects to Socket (without doing it on the client side)?

I see MyApp.Endpoint.subscribe/3, but not sure how to use it in the context of connecting to a Socket. For some background, I’m creating a WebSocket API and there are some endpoints that don’t really make sense in the traditional Phoenix Channel pattern.

One example is the client needs to fetch the server time once. I’d like the client to be able to fetch it without joining a Channel explicitly.

An alternative implementation for my needs might be to allow clients to send a message to a channel they haven’t joined yet, but from what I understand that doesn’t make sense since there wouldn’t be a process for that unjoined channel.

1 Like

Not possible with the channel architecture because the client must join a channel to understand what data they are receiving over it. If you want to reuse your existing websocket channel connection and fetch server time, can you simply push such interaction through an existing channel? Typically any moderately complex channel application ends up with a “control channel”, which I often name “UserChannel”, and this acts as a gateway for control information, such as user notifications or system-level events. That is likely your best option. if you don’t yet have a channel setup in place and are only wanting a server-time API, then I don’t think a websocket interface is needed as HTTP has you covered in that case.


Thanks for the info, it’s good to know what parts of my search I should prune.

Is there a way to automatically join a Channel on Socket connect, through something like an after-join callback? Maybe that’s a bad idea and I should just make the client explicitly join.

No, you must join from the client. From there, a single channel can subscribe to any number of external topics it wants, and proxy the messages via a push, but the client needs to join.


Thanks Chris!