Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node-Client-sessions vs express-session

I have this Node API that frontends a backend OAuth server. At the end of the SAML OAuth dance, I set the Bearer Token in a browser cookie.

// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());

// set a cookie
app.use(function (req, res, next) {
  // check if client sent cookie
  var cookie = req.cookies.cookieName;
  if (cookie === undefined)
  {
    // no: set a new cookie
    var randomNumber=Math.random().toString();
    randomNumber=randomNumber.substring(2,randomNumber.length);
    res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
    console.log('cookie created successfully');
  } 
  else
  {
    // yes, cookie was already present 
    console.log('cookie exists', cookie);
  } 
  next(); 
});


app.use(express.static(__dirname + '/public'));

Now I was introduced to a fancy NPM which does pretty much the same thing https://github.com/mozilla/node-client-sessions

While I was almost inclined on using this NPM, I bumped into express-session. https://github.com/expressjs/session - this is for server side sessions. But this also sets a cookie

    var express = require('express');
    var session = require("express-session");
    var app = express();


    app.use(session({
        resave: true,
        saveUninitialized: true,
        secret: 'ABC123',
        cookie: {
            maxAge: 60000
        }
    }));


    app.get("/test", function(req, res) {
        req.session.user_agent = req.headers['user-agent'];
        res.send("session set");
    });

If my need to set only a bearer token in the browser cookie for subsequent API calls, which option should be my choice?

like image 320
lonelymo Avatar asked Jan 08 '23 11:01

lonelymo


1 Answers

express-session is my go to.

If you look at what it took to accomplish the same thing with the two different methods, I think the answer is clear.

If all you want to do is set a client cookie that will enable the server to correctly authenticate future requests, express-session is awesome.

Here is an example set from another question I answered that uses MongoDB as a backend to store your sessions:

'use strict';

var express = require('express'),
  session = require('express-session'),
  cookieParser = require('cookie-parser'),
  mongoStore = require('connect-mongo')(session),
  mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/someDB');

var app = express();

var secret = 'shhh';

app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: secret,
  store: new mongoStore({
    mongooseConnection: mongoose.connection,
    collection: 'sessions' // default
  })
}));

// ROUTES, ETC.

var port = 3000;

app.listen(port, function() {
  console.log('listening on port ' + port + '.')
});
like image 73
Huston Hedinger Avatar answered Jan 11 '23 19:01

Huston Hedinger