Sessions

Providing state to the server

HTTP is stateless

Remember, an HTTP request is just a string.

GET / HTTP/1.1
Host: localhost
Cookie: theme=light; sessionToken=abc123

But I only need to log in once...

True, you only need to provide your credentials once, but how does the server remember that you've logged in?

Cookies are only a part of the whole picture.


You shouldn't trust cookie values for everything.

Data integrity

Since client information is unreliable, we use sessions to store information on our servers.

Global app state

var user = { username: 'bob', email: 'bob@example.com' };

app.get('/profile', function (req, res) {
  res.render('profile', user);
});

Global app state

const users = [
    { username: 'bob', email: 'bob@example.com' },
    { username: 'alice', email: 'alice@example.com' }
];

app.get('/profile', function (req, res) {
  var id = req.cookies.id
  res.render('profile', users[id]);
});

Redis

A solution to a problem?

  • Redis is an in-memory data store
  • Offers persistent storage
  • Fast

Sessions

By Tony Gaskell

Sessions

  • 1,529