Next.js Discord

Discord Forum

Safe ways to pass Http-Only Session Cookie value to client-side socket.io-client io() in useEffect()

Unanswered
Bighead carp posted this in #help-forum
Open in Discord
Bighead carpOP
Hi, I am using socket.io-client in Nextjs, I want to use its auth feature with my Http-Only secure session cookie, what I am not sure is the way to get it's value and pass it to the socket.io-client io() constructor

Should I fetch it with a Nextjs server-side api call and pass it to the io() constructor all in the useEffect()?

will fetching the session cookie value and passing it to client-side io() constructor in useEffect() this way be safe?

6 Replies

Crucian carp
You must not fetch the session cookie and pass it to socket.io-client.
HttpOnly cookies exist preciself to prevent javascript from reading them.
But you should let the browser automatically send the httponly cookie with the Websocket/http request and need to validate the session on your server.
That's all my thought.
Bighead carpOP
but there is no way to send it client-side?
the socket.io-client needs to be able to send the value in the session cookie with the auth attribute in its io() constructor
Bighead carpOP
anyone can answer this?
@Crucian carp You must not fetch the session cookie and pass it to socket.io-client. HttpOnly cookies exist preciself to prevent javascript from reading them. But you should let the browser automatically send the httponly cookie with the Websocket/http request and need to validate the session on your server.
Bighead carpOP
After a user is successfully authenticated the access token/session token will be stored in a Http-only cookie server-side of nextjs, the access token/session token will be pass back and forth for every api calls to the nodejs server on the server-side of nextjs, but socket.io const socket = io("https://api.example.com", { ... {) is on nextjs client-side, so how do I pass that access token / session token to the io() initialization script on nextjs client-side?