Scalable session handling in Node.js with Firebase

Firebase is awesome. It's one of those rare new tools that I knew right away would be so helpful. Once you use it, you'll know what I mean - I was hooked instantly.

They make it super easy to build an app without worrying about the database management or access points. The thing I love is that you can use any Firebase URL as a REST endpoint - you just add ".json" to the end of the URL. For example, if I create a Firebase called hackly to store my widgets, I can get widget 123 by going to:

Firebase for Node.js sessions

One way I've used Firebase is for storing session data in Node.js. If you use Connect or express, sessions are stored in memory by default, but this isn't ideal for production environments.

Warning: connection.session() MemoryStore is not designed for a production environment, as it will leak memory, and obviously only work within a single process.

If you add another server to balance the load, or if you restart node, you lose your sessions.

There are some good alternative session stores available, for example for redis or mongodb (I also created one for Amazon's DynamoDB), so why not one for Firebase?

Firebase is great for storing your sessions because it is easy - nothing to install and manage - and it's fast (and free, at least for the development plan). And it makes your app's session handling more reliable and scalable.

So I created connect-firebase. To use it you can just install the library via npm:

$ npm install connect-firebase

And then include the firebase_url option in your code. For example, with express:

var options = { firebase_url: '' };
FirebaseStore = require('connect-firebase')(express);
var app = express(
    express.session({ store: new FirebaseStore(options), secret: 'keyboard cat'})

Firebase also has a security api where you can fine-tune the read/write authorizations using simple javascript-like expressions. So if you don't want your sessions to be publicly accessible, you would add something like this:

   "rules": {
       // only authenticated users can read or write to my Firebase
       ".read": "auth !== null",
       ".write": "auth !== null"

And then you will need to add the optional token parameter to the FirebaseStore initialization options:

var options = { 
    firebase_url: '',
    token: 'qKtOKAQSTCxLFJI7uSeof6H7cfLpSuWYOhqOTQqz'