Skip to content

Commit

Permalink
docs: use io.engine.use() with express-session
Browse files Browse the repository at this point in the history
Related: #4819
  • Loading branch information
darrachequesne committed Sep 13, 2023
1 parent fd9dd74 commit 8259cda
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 31 deletions.
4 changes: 4 additions & 0 deletions examples/express-session-example/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@
socket.on("disconnect", () => {
ioStatus.innerText = "disconnected";
});

socket.on("current count", (count) => {
ioCount.innerText = count;
});
</script>
</body>
</html>
34 changes: 4 additions & 30 deletions examples/express-session-example/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ app.post("/incr", (req, res) => {
const session = req.session;
session.count = (session.count || 0) + 1;
res.status(200).end("" + session.count);

io.to(session.id).emit("current count", session.count);
});

app.post("/logout", (req, res) => {
Expand All @@ -35,37 +37,9 @@ app.post("/logout", (req, res) => {
});
});

const io = new Server(httpServer, {
allowRequest: (req, callback) => {
// with HTTP long-polling, we have access to the HTTP response here, but this is not
// the case with WebSocket, so we provide a dummy response object
const fakeRes = {
getHeader() {
return [];
},
setHeader(key, values) {
req.cookieHolder = values[0];
},
writeHead() {},
};
sessionMiddleware(req, fakeRes, () => {
if (req.session) {
// trigger the setHeader() above
fakeRes.writeHead();
// manually save the session (normally triggered by res.end())
req.session.save();
}
callback(null, true);
});
},
});
const io = new Server(httpServer);

io.engine.on("initial_headers", (headers, req) => {
if (req.cookieHolder) {
headers["set-cookie"] = req.cookieHolder;
delete req.cookieHolder;
}
});
io.engine.use(sessionMiddleware);

io.on("connection", (socket) => {
const req = socket.request;
Expand Down
2 changes: 1 addition & 1 deletion examples/express-session-example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@
"dependencies": {
"express": "~4.17.3",
"express-session": "~1.17.2",
"socket.io": "~4.4.1"
"socket.io": "^4.7.2"
}
}

0 comments on commit 8259cda

Please sign in to comment.