Configure Sessions in Node.js
Note
This feature is present in NCache Enterprise only.
NCache has to be configured in Node.js application's config.json file by providing the cacheName and other related properties. Following is a sample json file explained.
{
"ncacheStore": {
"ttl" : 3600,
"cacheName" : "myCache",
"disableTouch" : false,
"sessionTag" : "sess"
}
}
Properties added in the file are explained as under:
- cacheName is the name of your cache being used.
- ttl , time-to-live, means the total time for which session would remain in the NCache store.
- sessionTag is the tag associated with the session with which you can identify a session.
- disableTouch by default is false, which means that the session is being refreshed every time you try to access it.
Note
The properties ttl, sessionTag, disableTouch, if not provided by you, will be set with default values by express itself.
User can retrieve their data by using GetByTags in NCache Tags API.
Configurations also have to be done for the NCache Store and session middleware in the express.js file like given below.
const express = require('express');
const session = require('express-session');
const NCacheStore = require('ncache-sessions')(session);
const app = express();
// create store for NCache
const store = await NCacheStore.createStore(config.ncacheStore);
// Configure session middleware
app.use(session{
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
store: store
})
- Session middleware is created using the line below.
var session = require('express-session')
- NCache store is created using the createStore method in the express.js file.
const store = await NCacheStore.CreateStore(config.ncacheStore);
- Session being made through the express-session middleware will use NCache store as its custom store along with other properties shown below.
app.use(session{
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
store: store
})
Hence, after doing all the configurations above, the session data of your web application will now be stored in NCache which is a distributed and highly scalable cache store.