Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save and retrieve session from Redis

I am trying to integrate Redis sessions into my authentication system written in Node.js.

I have been able to successfully set up Redis server, connect-redis and Express server.

Here is my setup (just the important bit):

var express = require("express"); var RedisStore = require("connect-redis")(express); var redis = require("redis").createClient();  app.use(express.cookieParser()); app.use(express.session({     secret: "thisismysecretkey",     store: new RedisStore({ host: 'localhost', port: 6379, client: redis }) })); 

Now... How do I actually create, read and destroy the session? I have read tons of articles on how to setup connect-redis and many questions here on SO, but I swear each one stops on just the configuration and does not explain how to actually use it...

I am aware that that is probably extremely simple, but please don't downvote and just explain :).

like image 201
Eleeist Avatar asked Dec 23 '12 20:12

Eleeist


People also ask

Can we store session in Redis?

Redis is perfect for storing sessions. All operations are performed in memory, and so reads and writes will be fast. If you cannot afford losing any sessions, set appendfsync always in your configuration file. With this, Redis guarantees that any write operations are saved to the disk.

How do I use Redis cache for session management?

To add support of Redis you have to use Redis client and connect-redis. Create express-session and pass it to connect-redis object as parameter. This will initialize it. Then in session middleware, pass the Redis store information such as host, port and other required parameters.

How do I run a Redis session?

So you need to install connect-redis and pass your express-session instance to it. Then in middleware initialize redisStore with server details like this. app. use(session({ secret: 'ssshhhhh', // create new redis store.

Where session is stored Nodejs?

Session data is stored server-side. The default server-side session storage is MemoryStore."


1 Answers

That should be all there is to it. You access the session in your route handlers via req.session. The sessions are created, saved, and destroyed automatically.

If you need to manually create a new session for a user, call req.session.regenerate().

If you need to save it manually, you can call req.session.save().

If you need to destroy it manually, you can call req.session.destroy().

See the Connect documentation for the full list of methods and properties.

like image 102
JohnnyHK Avatar answered Sep 23 '22 06:09

JohnnyHK