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 :).
You can also use the Redis monitor tool to see all the action in real time! When you refresh your app you will see the data appear in the console window.
Sample Output for Sessions using tj/connect-redis
Consider this code.
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.
I put ttl to 260, you can increase. After TTL reaches its limits, it will automatically delete the redis key.
In routers you can use req.session variable to SET, EDIT or DESTROY the session.
One more thing...
If you want custom cookie i.e not as same as in your Redis store you can use cookie-parser to set cookie secrets.
Hope it helps.
link : https://codeforgeek.com/2015/07/using-redis-to-handle-session-in-node-js/
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.