Possible to create many app.get calls with express.js through for loop?

this is my first post so thanks in advance for the help :)

I'm trying to make my main.js file and to make things easier I want to do something like this:

var pages = {
"/profile":{"page":"My Profile","loc":"./contentPages/profile"},
...
...
...
};

for (var item in pages) {
    app.get(item, function(req, res){
        if(req.session.user_id == null){
            res.redirect('/');
            return;
        }


        res.render(pages[item].loc, {
        title:pages[item].page,
        thisPage:pages[item].page
        });
    });
}

right now no matter what happens whatever I have last in the dictionary is the the page which is always rendered. Is there a way to do something like this or must I write out every page I want to create?

Thanks so much!

The problem is that all the closures created by function(req, res) refer to the same variable (item) so they all use whatever value it has when they're called rather than what it had when they were created, and that's going to be the last one.

Most straightforward workaround is to create the closures with a helper function:

function makeHandler(item) {
  return function(req, res) {
     // copy body of handler function here
  };
}

and then replace the body of your loop with:

app.get(item, makeHandler(item));

Now each handler gets its own private copy of item which always retains the value it had when it was created.

You could also use an immediate function invocation to create the closures, but that would make the code look a little more cluttered.