0

have a server that uses socket.io. When a user connects it will assign them the user id thats made on the server then increment it by 1 so the next user with have a different id.

I want to use cookies for this, to check if they have previously logged in, if so, use that id, if not, use the one on the server.

the way to create a cookie is by using

res.cookie('cookie', 'monster')

but im not where i would put it, i tried putting it in the connect function but res wouldnt exist. and if i put it outside the function, how would i call it? Here is my code. This is the start of my server:

//Require npm modules
var express = require('express'); 
var http = require('http');
var events = require('events');
var io = require('socket.io');
var ejs = require('ejs');
var app = express();

//Set the default user Id to 1 and the default username to Guest
exports.Server = Server = function()
{
    this.userId = 1;
    this.userName = "Guest";
};

app.set('view engine', 'ejs');
app.get('/game/:id', function (req, res)
{
    res.render('game', {game: req.params.id});
});


Server.prototype.initialise = function(port)
{
    //Create the server using the express module
    this.server = http.createServer(app);

    //Declare the 'public' folder and its contents public
    app.use(express.static('public'));  

    //Listen to any incoming connections on the declared port and start using websockets
    this.server.listen(port);
    this.startSockets();
    this.em = new events();

    consoleLog('SERVER', 'Running on port: ' + port);
};

Server.prototype.startSockets = function()
{
    //When a user connects to the server on the 'game' socket
    this.socket = io.listen(this.server);

    this.socket.of('game').on('connection', function(user)
        {
            res.cookie('cookie', 'monster')
            //Set their usedId and username
            user.userId = this.userId;
            user.userName = this.userName + " " + this.userId;

            //Increment the user id by 1 so each user with get a unique id
            this.userId++;

            //Send a response back to the client with the assigned username and user id and initialise them
            user.emit('connected', user.userId, user.userName);
            this.em.emit('initialiseUser', user.userId, user.userName);

So where i have the res.cookie is where i want to be able to read and write cookies, any help is appriciated

Slavik Ribz
  • 165
  • 12

1 Answers1

1

I think what you are looking for is the middleware pattern employed by express. You can define as many of these middleware calls as you wish, and they are the perfect scope for calling any other functions which may need the res instance (or the req instance for that matter).

app.use(function (req, res, next) {
  // call function, passing in res here
  next();
})

Reference: https://expressjs.com/en/guide/using-middleware.html

EDIT:

This answer is not correct for your situation. In a node/express server not using socket connections, then yes, you could easily use the above pattern anywhere you need the request and response objects in scope.

However, once you setup the socket io server, the game changes. During the socket communications, there are no express request and response objects in scope anymore, everything is handled directly between your socket handling code and the client. So the answer is you need to handle the situation in a socket io way, not in an express way.

Please see: Adding a cookie value on Socket.IO

John McMahon
  • 1,605
  • 1
  • 16
  • 21
  • I tried this, it runs a total of 7 times when i connect for some reason. How would i set the users id from in here though? – Slavik Ribz Aug 07 '17 at 01:09
  • Ah ok, so you need to think about the socket io connections separate from the express routing of requests and responses. Once that socket connection is made, think of it as a direct connection to your socket handling code, meaning there will NOT be res or req instances, but at that point you don't need them. When you do a socket emit, you can send back any data you want. Your code receiving data on the other end can then decide to set a cookie on the client when it sees a certain category of emit, like "connected" in your code example. – John McMahon Aug 07 '17 at 01:21
  • ok so are you saying as soon as the client is loading is should check for a cookie id client side and send the id to the connect function in the server. Then if the id is in an id array on the server, log them in with that user id. i think that could work ill give that a try – Slavik Ribz Aug 07 '17 at 01:30
  • Probably many ways to achieve your goal. Please see my edited answer. – John McMahon Aug 07 '17 at 01:38