Configure Node.js Sessions
NCache provides a session store for Express applications through the ncache-sessions package. This page explains how to configure the store and register it with express-session so that session data is shared across your web application instances.
Important
Ensure the following development tools are installed on your Linux system when using NCache Node.js:
- g++
- make
Prerequisites
- Install and include the following module in your application based on your NCache edition:
- NCache: ncache-sessions
- Install Express and express-session.
- Include the following classes in your application:
- The cache must be running.
- For API details, refer to: Cache.
Configure the NCache Session Store
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" : "defaultCache",
"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
- If
ttl,sessionTag, ordisableTouchis omitted, the NCache session store uses its defaults. - The user can retrieve their data by using GetByTags in NCache Tags API.
Configure Express Session Middleware
Create the NCache store and pass it to the express-session middleware in your express.js file.
const express = require('express');
const session = require('express-session');
const NCacheStore = require('ncache-sessions')(session);
const app = express();
const config = require('./config.json');
async function configureSessions() {
// 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
}));
}
configureSessions().catch(console.error);
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
The express-session middleware uses the created NCache store for session persistence. Register the middleware before adding routes that access session data.