If you truly want to access the session data from everywhere as well as other request data using node through globals you might want to consider spawning a worker process for each request and declaring those as globals.
However that is not the "node way"(tm) of doing things, as the http server itself is part of your program and not a web server that is spawning a process to run your script (except for ReactPHP which behaves like nodejs).
Every connection handler gets the request and the output response as parameters, thus they are not accessible unless you forward them to your function calls.
const PORT = 80;
async function connectionHandler(req, res) {
/* here you implement routing
* depending on req.url, req.method, req.headers, etc...
*/
}
http.createServer(connectionHandler).listen(PORT);
Here what you might need is an object (associative array) with session_id as key and an object as value. And if the user doesn't have a session_id yet you create it:
const _SESSION = {};
function sessionStart(headers) {
let id = headers.cookies?.piles_awesome_session_id ?? null;
if (!id) {
id = generateSessionId();
_SESSION[id] = {};
}
return id;
}
function generateSessionId() {
const chars = [[49,57],[97,102]].map(([start, end]) => Array(end-start+1).fill(null).map((n,i) => String.fromCharCode(n+i))).flat();
return Array(32).fill(null).map(c => chars[Math.floor(Math.random()*chars.length)]).join('');
}
You'd call that by passing req.headers to it inside the connection handler or any route handler if you're using express or a custom router.
function connectionHandler(req, res) {
const sessionId = sessionStart(req.headers);
const session = _SESSION[sessionId];
// don't forget to set the cookie
// "piles_awesome_session_id"
}
Ideally you'd use a database for storing your session across multiple server instances instead of a variable in memory. Just remember server vars are not request scoped, they will leak between different users, that's why request and response are not globals.