express.js is a framework for creating web applications with node.js. It is very similar to Sinatra for Ruby.
Riak is a NoSQL key-value store built on Erlang with a nice HTTP interface. There is a Javascript library called riak-js that can be used within node.js to communicate with a Riak database. As part of the riak-js package, there is a session store so that express can store HTTP session information in Riak.
Express uses connect middleware which ships with a default session store called MemoryStore. As the name implies, it simply stores the session in memory. Obviously, while you can use this in development, it is not production-safe as it will leak memory and the session data will only be kept in a single node.js process. Even in development mode, you might not want to use it because everytime you kill your node.js server you will have to login again.
There are other session stores available such as a cookie session store, and session stores for other databases such as MongoDB, CouchDB, Redis, etc... The list is available here: https://github.com/senchalabs/connect/wiki.
For the project, I'm working on, we are using Riak as our database so it made sense to also store our session information in Riak so we've decided to use the Riak session store from riak-js.
To use it, add the following lines on top of your express main file: app.js.
var riak = require('riak-js'), db = riak.getClient({port: 8098, debug: false}), riakSessionStore = riak.getSessionStore({client: db});Then, when you are configuring your express application, use it as shown below:
app.configure(function(){ // ... app.use(express.bodyParser()); app.use(express.cookieParser()); app.use(express.session({secret: 'keyboard cat', store: riakSessionStore })); // ... });Note that it is important that you have the cookieParser before the riakSessionStore since the session id is saved in a cookie.
At the time I wrote this post, the npm package for riak-js is not up-to-date so for this to work correctly, you will need to install riak-js from source and make sure you have the latest and greatest from github which has this patch that fixes a but in the session store. Follyow the instructions on the riak-js README file to install it from source. When you want to use the package, create a symbolic link from your node_modules folder to where you keep your copy of riak-js.
That's all. I hope this post will be useful to you if you are trying to use the Riak session store with node.js.

0 comments:
Post a Comment