Simply assign an empty object:
req.session = {};
... and the garbage collector will do the rest automatically.
UPDATE: Since this answer is disputable, I would like to provide some more details on the point.
The solution given above will do the job for the author in the current situation, as well as any other valid solution provided in this question. It mainly depends on the way how the developer wants to manipulate the deprecated data.
Session object may contain data that is linked by different variable, and setting a new empty object to req.session
will not break the reference to the old data, so the old data will be available where it is still required. Although the correct way to keep old data is to clone the initial object, real life scenarios can be different. Let's look at the following example:
req.session.user = { name: 'Alexander' }; // we store an object in the session
var session = req.session; // save reference to the session in a variable
console.log( req.session, session ); // {user: Object}, {user: Object}
req.session = {}; // let's replace session with a new object
console.log( req.session, session ); // {}, {user: Object}
We still can fetch old data from session
variable but req.session
is empty: here setting a new object works as sort of alternative to deep cloning. The garbage collector will not remove data from old req.session
object as it is still referenced by session
variable.
Deep cleaning of the object with method provided by @Dave or shorter via Object.keys
(which ignores properties in the prototype chain and doesn't require any shims for node.js):
Object.keys(object).forEach(function(key) { delete object[key]; });
... will explicitly remove all values from the req.session
object and, since session
variable is linked to the same object, session
will become empty as well. Let's see how it works:
req.session.user = { name: 'Alexander' }; // we store an object in the session
var session = req.session; // save reference to the session in a variable
console.log( req.session, session ); // {user: Object}, {user: Object}
Object.keys(req.session).forEach(function(key) { delete req.session[key]; });
console.log( req.session, session ); // {}, {}
As you can see now, in both cases we get empty objects.
From speed and memory perspectives setting new empty object will be much faster than cleaning the old object property by property, however memory-wise if old data is still referenced somewhere, the new object approach won't free up memory that old data is consuming.
It's quite obvious that choosing the approach to take is mostly up to your coding scenario, but in most cases req.session = {};
will do the job: it is fast and short. However, if you keep references to the original object in other variables, you may consider using deep implicit object properties deletion.