rendrjs / rendr

Render your Backbone.js apps on the client and the server, using Node.js.
MIT License
4.09k stars 313 forks source link

Unnecessary server sessions [fix] #509

Open rodeyseijkens opened 8 years ago

rodeyseijkens commented 8 years ago

I think this is worth sharing.

By default the rendr server side is creating a new session every time it is doing stuff. Every visit or hard page refresh. This of course isn't really nice especially if you store it in a database for example because the a lot of unnecessary sessions are stored.

var sessionMiddleware = session({
    secret: config.server.session.secret,
    cookie: { maxAge: 24 * 60 * 60 * 1000 * 14 },
    secure: true,
    store: new MongoStore({ mongooseConnection: mongoose.connection }),
    resave: false,
    saveUninitialized: false
});

// Do not make a session when its the server or when it is a bot
app.use(function useSession(req, res, next) {
    var userAgent = req.headers['user-agent'],
          isBot = (/bot|googlebot|crawler|spider|robot|crawling/i.test(userAgent)),
          isServer = (userAgent == "Rendr RestAdapter; Node.js");

    if (!isBot && !isServer) {
        return sessionMiddleware(req, res, next)
    }

    next()
});
pjanuario commented 8 years ago

:+1:

bigethan commented 8 years ago

Shouldn't the middleware see the session cookie when the client app is communicating to the server and not create a new session? Or am I missing something?