This tutorial shows how to use Serverless Redis as your session storage for your Express Applications.

See the code

Step-1: Create Project

Create a folder for your project and run: npm init

Step-2: Install Redis and Express

In your project folder run: npm install express redis connect-redis express-session

Step-3: Create a Redis (Upstash) Database For Free

Create a database as described here.

Step-4: index.js

In Upstash console, click the Connect button, copy the connection code (Node.js node-redis). Create index.js file as below and replace the Redis connection part.

var express = require("express");
var parseurl = require("parseurl");
var session = require("express-session");
const redis = require("redis");

var RedisStore = require("connect-redis")(session);
var client = redis.createClient({
  // REPLACE HERE
});

var app = express();

app.use(
  session({
    store: new RedisStore({ client: client }),
    secret: "forest squirrel",
    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 the app

node index.js

Step-6: Check your work

Open http://localhost:3000/bar and http://localhost:3000/foo in different browsers. Check if the view-count is incrementing as expected.

FAQ:

There is a default session storage of express-session. Why do I need Redis?

Default session store loses the session data when the process crashes. Moreover, it does not scale. You can not utilize multiple web servers to serve your sessions.

Why Upstash?

You can use any Redis offering or self hosted one. But Upstash’s serverless approach with per-request-pricing will help you to minimize your cost with zero maintenance.

How to configure the session storage?

See here