Node.js use Redis as Session storage

        In previous post, we use default Session storage to test. However, it is not suitable in production stated by the developer.

"Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing. "

         In this post, I will use Redis (famous and widely-used in-memory store) as the storage of Session. We can also the module connect-redis in express-session npm package webpage. We modify the code(v2.3) in post Node.js use passport with LocalStrategy in Authentication Part 4. It use session to use login user information and failure messages.

         If you just follow the steps in connect-redis webpage and run, you will find connect error message in terminal.

import {RedisStore} from "connect-redis"
import session from "express-session"
import {createClient} from "redis"

// Initialize client.
let redisClient = createClient()
redisClient.connect().catch(console.error)

// Initialize store.
let redisStore = new RedisStore({
  client: redisClient,
  prefix: "myapp:",
})

// Initialize session storage.
app.use(
  session({
    store: redisStore,
    resave: false,
    saveUninitialized: false,
    secret: "keyboard cat",
  }),
)

        It is because we haven't installed the redis server in our machine. We go to the Redis (open-source) official page for the instruction to install. I'm using ubuntu 24.04 now but I follow the installation step with APT

sudo apt-get install lsb-release curl gpg
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
sudo chmod 644 /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
sudo apt-get update
sudo apt-get install redis

        After install, we should be able to run our code without error message now.

        If we login successfully, postman will get /secrets page message. The terminal also print out the content of Session saved by the passport module.

        We also can get message if we directly access GET /secrets (not send username and password in the body) after login

        If we clear postman cookie and then login with wrong password, the server return the "incorrect password" message to postman.

The session data remain even restart node.js

        If we use postman login before and does not clear the cookie, we still can access GET /secrets page even we had terminate node.js and restart it. It is because the session data is stored in Redis now (separated storage space).

Browser the content in Redis

         We can view the redis in Visual Studio Code with extension plugin. We click on the extension button on the left panel of VS code and type in the keyword redis to search the plugin. I have installed the first one.
        Now a new icon will appear on the left panel under database icon. Click this new button and click the "Create Connection" button
 
        Below tab is opened. We select Redis as the Server Type and keep others default. Then we click the "+connect" button at the bottom.

        Now we will see a connection appear in left hand side.


         We browse it and can see our Session content. "mysession" is the prefix we defined when create the redisStored in our code. The storage space name "0" because we don't pass any setting to createClient of redis module. 
        To connect different space, we can pass a object with 'url' property name and value redis[s]://[[username][:password]@][host][:port][/db-number] . For more detail, we can refer to redis npm package page.    

        The source code used is uploaded to github
 

         

 

Comments

Popular posts from this blog

Use okhttp to download file and show progress bar

Download File into app specific storage with Retrofit

Unzipp file with Zip4j library