Why can't I access this cookie?
When the user logs in the cookie is recieved and sent back to the Express server.
When initializing a new websocket to the Socket.io server this cookie does not get sent, so I was trying to get it via the document.cookie. However, it did not work since the the cookie was not modifiable.
It is an HttpOnly cookie that cannot be accessed via client-side Javascript.
In other words: The server is able to read and manipulate the cookie. The client receives it and blindly sends it back with every subsequent request, without being able to read or manipulate its contents, at least not with Javascript means.
The official website did something that did not work for me. express session middleware
const session = require("express-session");
io.use(wrap(session({ secret: "cats" })));
io.on("connection", (socket) => {
const session = socket.request.session;
});
So, I got around it by making: Logic:
Before establishing websocket, request credentials to express endpoint "/userCredentials"
and then use these credentials to establish the connection
Warning: Down below code is stripped because I did so many auth logics
CLIENT:
...
useEffect(() => {
(async() => {
const pending_creds = await fetch("/userCredentials");
const creds = pending_creds.json();
const ws = io({auth: {creds}})
setSocket(ws)
})()
}, [])
...
SERVER:
...
app.get("/userCredentials", (req,res) => {
const userSession = req.session.user;
res.json(userSession)
})
...
io.use(socket, next){
const creds = socket.handshake.auth.userSession;
if(creds){
next()
} else {
socket.disconnect()
}
}