It is a truth universally acknowledged that some kind of stateful sessions are indispensable to any website with users. I’m familiar with the Node/Express ecosystem, so I’ll write specifics about that. The theory and debates underlying session architecture should transfer to other languages.

  1. What is State?
  2. Serverful Sessions
  3. HTTP-Only Cookies as Primary Keys
  4. What goes in a session object?
  5. Server-Side Session Stores
  6. Configuring express-session
  7. Serverless Sessions and JSON Web Tokens
  8. The Great Debate: Cookies vs. Tokens
  9. Resources

What is State?

According to Wikipedia, a program is described as stateful if it is designed to remember preceding events or user interactions; the remembered information is called the state of the system.

So, are websites stateful? The answer is, not stateful enough for a login-protected user system.

Client-side, front-end websites are local storage, the browser object model (BOM), the document object model (DOM) it contains (BOM vs DOM), and whatever HTML, CSS, JavaScript, etc that the server serves to the BOM. The BOM and the DOM have state, but it resets every time you reload the page.

Server-side websites use data and algorithms to transform inputs into outputs. They, too, (at least Node.js) only have enough state for a single request-response cycle.

Serverful Sessions

Given that websites are not stateful between page reloads on the front and request-response cycles on the back, what can we do to serve the illusion of continuity (a logged in state) across a series of request-response-reload cycles? A session in Express is a (Javascript) object that stores information that persists across a series of requests from one device’s browser. Your code stores values in the session object that help you to match that device to a certain user and the choices they’ve made since logging in.

Sessions are not a built-in feature of Express; they require configuring the express-session middleware on your express server instance (application-level middleware). More about middleware. We’ll take a crack at that once we have a fuller picture of what we’re doing.

HTTP-Only Cookies as Primary Keys

If you’ve worked with SQL databases at all, you’re familiar with the concept of primary keys. If you’re not familiar, a primary key is a number or string attached to some data that allows you to pick that entry out and identify it in another context.

Modern, HTTP-only cookies are the (encrypted) primary keys of sessions. Each Express session has a random id called the sid. When the Express session middleware is configured, the browser makes its first query to the server. The server responds with whatever you res.send or res.render and also sends a set-cookie response header with the encrypted sid to the browser. Your server’s response renders in the browser with whatever information you sent. But when it requests the next resource from your server, it sends back the sid in a cookie request header. If the server receives a cookie request header from the browser, it doesn’t send the set-header response header back. Read more about HTTP headers. That cookie header tells the server that the client belongs to the session with the same sid, so the server can pull up that user’s info from its session data.

“Old-school” cookies are stored in the DOM as the document.cookies object. HTTP-only cookies are not accessible to Javascript. So assholes can steal old-school cookies with cross-site scripting attacks, but not HTTP-only cookies. It’s possible to intercept HTTP headers, but it’s harder.

What goes in a session object?

Never store passwords, hashes, credit card data, or anything else obviously sensitive in a session object. What should you store in the session object? Anything non-sensitive that helps you identify the user and their attributes on the client or the server across a series of requests. This will be things like associated database keys or _ids, names, emails, what they had for lunch, etc. Sensitive info can be pulled from the database or microservice fresh on demand using keys/_ids and/or environment variables. Since you don’t actually send the session object to the client, but just the cookie, any session info that you want to send to the client has to be send in the response itself; the cookie is just an identifier to connect the client browser with the server session object.

Server-Side Session Stores

Great! Express can keep track of who makes what request, and you can carry tidbits of info around the server with you for that person. But what if you are running a cluster of machines and one goes down? What if a different instance of the server receives the second request from a client?

Session stores to the rescue! The session store is a super simple table/collection/hashmap in virtually any type of database that saves each session object. When the client sends a cookie header to the server, if the session is not in the server’s working memory, it checks the session store for the de-encrypted sid. It typically only has a couple columns/document keys – one for the sid, and one for a (possibly stringified) JSON-like object that is the session object. Express session stores are available for MySQL, MongoDB, Redis, and more — check them out at the express-session github page.

Configuring express-session

Below is a snippet from an express server configuration.

[pastacode lang=”javascript” manual=”console.log(%60Node%20environment%3A%20%24%7Bprocess.env.NODE_ENV%7D%60)%3B%0A%0Alet%20dotenv%3B%0Aif(process.env.NODE_ENV%20%3D%3D%3D%20’development’)%20%7B%0A%09%2F%2Fif%20you’re%20in%20development%2C%20use%20the%20development%20environment%20variables%0A%09dotenv%20%3D%20require(‘dotenv’).config(%7BBASIC%3A%20’basic’%2C%20path%3A%20′.%2Fenv%2F.env.dev’%7D)%3B%0A%7D%20else%20if%20(process.env.NODE_ENV%20%3D%3D%3D%20’test’)%20%7B%0A%09%2F%2Fif%20you’re%20in%20test%2C%20use%20the%20test%20environment%20variables%0A%09dotenv%20%3D%20require(‘dotenv’).config(%7BBASIC%3A%20’basic’%2C%20path%3A%20′.%2Fenv%2F.env.test’%7D)%3B%0A%7D%0A%2F%2Fif%20you’re%20in%20production%2C%20the%20environment%20variables%20will%20be%20set%20on%20the%20production%20machine%0A%0A%2F%2F%2B%2B%2B%2B%2B%2B%20express%20config%20%2B%2B%2B%2B%2B%2B%0A%2F%2Frouter%20and%20server%0Aconst%20express%20%3D%20require(‘express’)%3B%0A%2F%2Fpackage%20to%20parse%20requests%20sent%20to%20express%0Aconst%20bodyParser%20%3D%20require(‘body-parser’)%3B%0A%2F%2Finstantiate%20express%0Aconst%20app%20%3D%20express()%3B%0A%0A%2F%2Fset%20body%20parser%20on%20express%20middleware%0Aapp.use(bodyParser.urlencoded(%7B%0A%20%20extended%3A%20true%0A%7D))%3B%0A%0Aapp.use(bodyParser.json())%3B%0A%0A%0A%2F%2Fserve%20the%20static%20assets%20from%20the%20public%20directory%0Aapp.use(express.static(__dirname%20%2B%20’%2Fpublic’))%3B%0A%0A%2F%2F%2B%2B%2B%2B%2B%2B%20logging%20config%20%2B%2B%2B%2B%2B%2B%0A%2F%2F…%0A%0A%2F%2F%2B%2B%2B%2B%2B%2B%20database%3A%20mongoose%20connection%20for%20express%20sessions%20%2B%2B%2B%2B%2B%2B%0A%2F%2Fmongodb%20ORM%0Aconst%20mongoose%20%3D%20require(‘mongoose’)%3B%0A%2F%2FPromise%20library%20for%20mongoose%0Aconst%20Promise%20%3D%20require(‘bluebird’)%3B%0Amongoose.Promise%20%3D%20Promise%3B%0A%0A%2F%2Fcreate%20a%20mongoose%20connection%20from%20the%20connection%20address%20in%20the%20environment%20variable%0Amongoose.connect(process.env.MONGO_CONN%2C%20%7B%0A%09useMongoClient%3A%20true%0A%7D)%3B%0Aconst%20conn%20%3D%20mongoose.connection%3B%0A%0A%2F%2Fif%20there’s%20a%20connection%20error%2C%20log%20it%0Aconn.on(%22error%22%2C%20function(error)%20%7B%0A%09console.log(%22the%20database%20connection%20farted!%20Here’s%20how%3A%20%22%20%2B%20error)%0A%7D)%3B%0A%2F%2Fwhen%20the%20connection%20opens%2C%20log%20it%0Aconn.once(%22open%22%2C%20function()%20%7B%0A%09console.log(%22the%20database%20is%20connected!%22)%3B%0A%7D)%3B%0A%0A%2F%2F%2B%2B%2B%2B%2B%2B%20express%20sessions%20(remembering%20user%20data)%20%2B%2B%2B%2B%2B%2B%0A%0A%2F%2Fsession%20middleware%20package%0Aconst%20session%20%3D%20require(‘express-session’)%3B%0A%2F%2Fpackage%20to%20back%20sessions%20up%20to%20the%20database%0Aconst%20MongoStore%20%3D%20require(‘connect-mongo’)(session)%3B%0A%0A%2F%2Fdecode%20proxy%20value%20boolean%20from%20environment%20variable%20for%20options%20object%20below%0Alet%20proxyValue%20%3D%20false%3B%0Aif(process.env.PROXY_VALUE%20%3D%3D%20’1′)%20%7B%0A%09%2F%2Fif%20there’s%20a%20proxy%2C%20tell%20express%20to%20trust%20it.%20%20used%20in%20production%20when%20serving%20node%20with%20nginx%20or%20similar%0A%09app.set(‘trust%20proxy’%2C%201)%3B%0A%09proxyValue%20%3D%20true%3B%0A%7D%0A%0A%0A%2F%2Fset%20session%20middleware%20options%0Aapp.use(session(%7B%0A%09%2F%2Fencrypt%20the%20cookie%20with%20the%20session%20secret%20environment%20variable%0A%09secret%3A%20process.env.SESSION_SECRET%2C%0A%09%2F%2Fif%20the%20session%20wasn’t%20modified%2C%20don’t%20save%20it%20again%0A%09resave%3A%20false%2C%0A%09%2F%2Fdon’t%20save%20sessions%20with%20nothing%20in%20them%0A%09saveUninitialized%3A%20false%2C%0A%09%2F%2Fset%20the%20value%20for%20proxy%0A%09proxy%3A%20proxyValue%2C%0A%09%2F%2Fcookie%20options%0A%09cookie%3A%20%7B%0A%09%09%2F%2Fmust%20be%20served%20over%20https%0A%09%09secure%3A%20true%2C%0A%09%09%2F%2Fvalid%203%20days.%20%20this%20is%20the%20true%20expiration%20setting%0A%09%09maxAge%3A%201000%20*%2060%20*%2060%20*%2024%20*%203%2C%0A%09%09%2F%2Fi%20think%20there’s%20some%20bug%20that%20specifying%20this%20fixes%20but%20pretty%20sure%20it’s%20deprecated%0A%09%09expires%3A%20false%0A%09%7D%2C%0A%09%2F%2Fconfigure%20the%20session%20database%20collection%20connection%20and%20how%20long%20it%20retains%20sessions%0A%09store%3A%20new%20MongoStore(%7B%0A%09%09mongooseConnection%3A%20conn%2C%0A%09%09ttl%3A%2060%20*%2060%20*%2024%20*%203%2C%20%2F%2Fcookie%20valid%203%20days%0A%09%09%2F%2FautoRemove%3A%20’native’%0A%09%7D)%0A%7D))%3B%0A%0A%2F%2F%2B%2B%2B%2B%2B%2B%20authentication%20setup%20%2B%2B%2B%2B%2B%2B%0A%2F%2F…%0A%0A%2F%2F%2B%2B%2B%2B%2B%2B%20view%20engine%20setup%20%2B%2B%2B%2B%2B%0A%2F%2Fhandlebars%2C%20pug%2C%20isomorphic%20react%2C%20etc%0A%0A%2F%2F%2B%2B%2B%2B%2B%2B%20ROUTES%20%2B%2B%2B%2B%2B%2B%0A%0Aconst%20routes%20%3D%20require(‘.%2Froutes%2Froutes’)%3B%0A%0A%0A%2F%2Fpass%20express%20the%20routes%0Aapp.use(routes)%3B%0A%0A%2F%2F%2B%2B%2B%2B%2B%2B%20CONNECTION%20%2B%2B%2B%2B%2B%2B%0A%0Aconst%20PORT%20%3D%20process.env.PORT%20%7C%7C%203000%3B%0A%0A%0A%2F%2Fuse%20https%20in%20development%20and%20testing%2C%20proxy%20http%20for%20production%0Aif(process.env.NODE_ENV%20!%3D%20’production’)%20%7B%0A%09const%20fs%20%3D%20require(‘fs’)%3B%0A%09const%20https%20%3D%20require(‘https’)%3B%0A%09%2F%2Fself-generated%2C%20self-signed%20ssl%20certificates%0A%09const%20privateKey%20%20%3D%20fs.readFileSync(‘.%2Fssl.key’%2C%20’utf8’)%3B%0A%09const%20certificate%20%3D%20fs.readFileSync(‘.%2Fssl.crt’%2C%20’utf8’)%3B%0A%09%0A%09const%20httpsServer%20%3D%20https.createServer(%7Bkey%3A%20privateKey%2C%20cert%3A%20certificate%7D%2C%20app)%3B%0A%09%0A%09httpsServer.listen(PORT%2C%20function()%20%7B%0A%09%09console.log(%22express%3A%20secure%20development%2Ftest%20server%20listening%20to%20your%20mom%20on%20PORT%3A%20%22%20%2B%20PORT)%3B%0A%09%7D)%3B%0A%09%0A%7D%20else%20%7B%0A%09app.listen(PORT%2C%20function()%20%7B%0A%09%20%20console.log(%22express%3A%20production%20server%20listening%20to%20your%20mom%20on%20PORT%3A%20%22%20%2B%20PORT)%3B%0A%09%7D)%3B%0A%7D%0A%0A%0A%0A” message=”server.js” highlight=”43-46,57-98″ provider=”manual”/]

To generate your own development SSL certificates, check out my post.

Serverless Sessions and JSON Web Tokens

Used to be, cookies were the only way. With the rise of serverless architectures, “server” functions are even more stateless because there is no there there. Nothing connects the requests except the client device making them. JSON web tokens (JWT) have become increasingly popular because they store session info on the client. JWT are sent to the client on authentication, often from a SaaS like Auth0, and stored in the browser (or on the phone) actually containing the data of the session within the token itself. Obviously they are encrypted. The client sends the token to the various serverless API endpoints to identify itself and persist the session for the client and the “server”. JWT have headers, a payload, and a cryptographic signature. Once you’ve verified them on the client side, you can store them in local storage or an old-school cookie, although they can be quite large and old-school cookies have a size limit. JWT also expire just like server-side sessions can.

The Great Debate: Cookies vs. Tokens

I’m not a security expert, but my personal preference is to use server-side sessions with a store and HTTP-only cookies if I actually have a server, and JWT if I don’t. Storing session data on the client feels ookie to me unless I absolutely have to. There is no definitive answer as of this writing whether cookies or tokens are more secure. Developers have strong feels for and against both. Google around for more opinions.

Any cookie or token should ALWAYS be sent over HTTPS.

Resources

  1. Express Session Docs
  2. Robert Hafner for Treehouse on Secure Cookies (2009)
  3. Robert Hafner for Treehouse on Secure Sessions (2009)
  4. ExpressJS Book on Sessions (2013)
  5. Jonathan Kresner Express Sessions Deep Dive (2015)
  6. Decembersoft on Authenticating a Session Cookie in Express with JWTs (2017?)
  7. Introduction to JWTs (2017)
  8. Auth0 (authentication as a service with JWTs)