Configure Node.js Sessions
This page provides guidance on configuring NCache's Node.js sessions with Node.js applications to cache sessions as is detailed below along with the necessary prerequisites and middleware.
Note
This feature will only work with .NET applications that target the .NET 4.8 platform.
Prerequisites to Configure Node.js Sessions
- Install and include the following module in your application based on your NCache edition:
- Enterprise: ncache-sessions
- Include the following classes in your application:
- The cache must be running.
- For API details, refer to: Cache.
- To handle any unseen exceptions, refer to the Troubleshooting section.
NCache has to be configured in the Node.js application's config.json file by providing the cacheName and other related properties. Following is an explanation of a sample json file.
{
"ncacheStore": {
"ttl" : 3600,
"cacheName" : "demoache",
"disableTouch" : false,
"sessionTag" : "sess"
}
}
The properties added in the file are explained below:
- cacheName: The name of the cache in use.
- ttl: Also called time-to-live, this is the total time for which the session would remain in the NCache store.
- sessionTag: This is the tag associated with the session that you can use to identify a session.
- disableTouch: This is set to False by default, 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. - The 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 as 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
})
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
- 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 the NCache store as its custom store along with other properties shown below.
app.use(session{
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
store: store
})
So provided you have performed all the configurations above, your web application session data will now be stored in NCache (a distributed and highly scalable cache store).