loading...
Cover image for Express Session with Serverless Redis
Lambda Store

Express Session with Serverless Redis

svenanderson profile image Sven Anderson Updated on ・3 min read

In this post, I will write an Express web application which keeps session on Redis (Lambda store). The example will keep the view count of the user in session and display it.

Alt Text

Now, let's walk through the application in 5 steps:

Step 1- Install node and express as described here

Step 2- Install redis, express-session and connect-redis inside your app's folder
npm install redis connect-redis express-session

Step 3- Start a free Redis database in Lambda Store

Step 4- In your app folder, copy the following code into index.js. You need replace your lambda store parameters for redis client.

var express = require('express')
var parseurl = require('parseurl')
var session = require('express-session')
const redis = require('redis')

var RedisStore = require('connect-redis')(session)
var redisClient = redis.createClient ({
    host : 'YOUR_ENDPOINT',
    port : 'YOUR_PORT',
    password: 'YOUR_PASSWORD'
});


var app = express()

app.use(session({
    store: new RedisStore({ client: redisClient }),
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
}))

app.use(function (req, res, next) {
    if (!req.session.views) {
        req.session.views = {}
    }

    // get the url pathname
    var pathname = parseurl(req).pathname

    // count the views
    req.session.views[pathname] = (req.session.views[pathname] || 0) + 1

    next()
})

app.get('/foo', function (req, res, next) {
    res.send('you viewed this page ' + req.session.views['/foo'] + ' times')
})

app.get('/bar', function (req, res, next) {
    res.send('you viewed this page ' + req.session.views['/bar'] + ' times')
})

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

Step 5- Run your application node index.js and open http://localhost:3000/bar and http://localhost:3000/foo in different browsers and check if the view-count is incrementing as expected.

Now. let's answer some questions:

Is not the default session storage of express-session enough?

Yes, MemoryStore (that is the default session storage of express-session) also works for this example. But you need a real session store for production use case. Why?
1- With default session store, when you process crashes you lose the session data.
2- It does not scale. When you have multiple servers with a load balancer, the load balancer can send the subsequent requests to different servers. So if a user has created shopping basket and added an item in server-1. If the second request goes to server-2; the user will see the shopping basket empty.

There are ways to configure the load balancer accordingly (sticky session) but still the scalable approach is to use a distributed session storage.

In this application, we store user session in Redis (in Lambda Store).
Alt Text

Why Redis?

Redis is a in-memory key-value store. It is probably the most popular choice as session storage. It has very low latency and very lightweight. In the list of session-stores, it is the most popular one by far.

Why Lambda Store?

I see some people think that maintaining a Redis server for session management is an overkill. There are cloud (managed) options such as Elasticache and RedisLabs. But because their pricing is based instance-memory usage, it is costly most of the time. Lambda store gives you Redis with serverless pricing. That means you pay only when and what you use. See my blog post, where I introduce Lambda Store in detail.

What is next?

  • You can learn more about how to configure your session middleware here
  • Have a look at documentation of Lambda Store.
  • I will post blogs about how to manage sessions for JAMStack applications and serverless applications. If you are interested follow us.

Posted on by:

svenanderson profile

Sven Anderson

@svenanderson

Making the world serverless

Lambda Store

Lambda Store is the first the `serverless Redis` service. In this blog, Lambda Store engineering team shares their experiences on Cloud, AWS, Kubernetes, Redis and of course Lambda Store.

Discussion

markdown guide