Hello, I am trying to build a Backend system in Phoenix, this is mostly APIs but needs Websockets for a chat interface.
I researched a bit with Claude, and found out that Phoenix sockets can be a great choice for this with Channels, so I create a setup as details below.
I have two tables
chat_sessions
chat_messages
When the user lands on /api/v1/chat/sessions
, I check for a few things and then create a record in this table, and I use put_session
to set the id of this table in a cookie and send it back to the client.
Now I created a socket
endpoint in the endpoint file similar to /live
just under /live
socket "/api/chat", ProfiWeb.UserSocket,
websocket: [connect_info: [session: @session_options]],
longpoll: false
Inside the UserSocket
I added
def connect(params, socket, connect_info) do
Logger.info("WebSocket connection attempt with params: #{inspect(params)}")
Logger.info("Connect info session: #{inspect(connect_info[:session])}")
with {:ok, session_id} <- extract_session_id(connect_info),
....
...
defp extract_session_id(connect_info) do
case connect_info[:session] do
%{"chat_session_id" => id} when is_binary(id) ->
Logger.info("Found chat_session_id in session: #{id}")
{:ok, id}
_ ->
Logger.info("No session found, checking params for session_id")
{:error, :no_session_id}
end
end
Backend is running on http://localhost:4000 and FE is on http://localhost:4321
I was hoping this setup would be enough and I will get the cookie since inside session options, same_site is set to “Lax”
@session_options [
store: :cookie,
key: "_profi_key",
signing_salt: "4yRHL+9g",
same_site: "Lax"
]
But when I check the request headers in browser, I don’t see the cookie, googling and going back and forth with Claude, finally landed on creating a reverse proxy on localhost:3000 and proxying both through that.
When I do that, browsers start sending the cookie, but the server still doesn’t get it.
I fought this problem a lot, with Claude a lot but nothing worked, added a ton of logs but nothing.
Does anyone know how I can do this ?
Thank you for your help, much appreciated
Phoenix Forum > Questions / Help
EDIT: If I missed any details, please let me know, I will update the post with those details.