How do I keep a session variable from changing?

So I've got a session variable, req.session.user, that contains an object corresponding to a user account. When I do this,

var user = req.session.user;
var fakeUser = user;
fakeUser.username = 'bob';

user.username and req.session.user.username both get changed to 'bob' as well. How do I prevent this?

When you write var fakeUser = user you copy reference to the object user - fakeUser is still referencing the same object.

If you want copy the object, you have to clone it or copy only desired properties of the user: e.g.:

var fakeUser = {
  name: user.name,
  id: user.id
}

JS clonning is described in following answers:

answer 1 answer 2

You can also use a clone method of underscore library (But be aware that it does just a shallow copy (not deep) - i.e. if user object contains some references, they are copied as references).

Simple method to clone object is to just serialize and deserilaze it (but this will not work on circular references - when object is referencing itself or it's part):

function clone(a) {
   return JSON.parse(JSON.stringify(a));
}

Clone it

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}