Sunday, 15 February 2015

node.js - express session store user agent -



node.js - express session store user agent -

i set session management in node js/ express js website successfully. stores session info in mongo db. want session valid users log in couple of weeks. code follows:

var cookieparser = require('cookie-parser'); var session = require('express-session'); var mongostore = require('connect-mongo')(session); app.use(cookieparser()); app.use(session({ store: new mongostore({ mongoose_connection: db }), secret: 'cookie_secret', cookie: { maxage: null } }));

it works fine normal users, problem web crawlers such google bots , facebook bots. still want them crawl website don't want sessions stored in mongo db. it's taking lots of space , storage increasing daily costs me money.

how selectively take sessions stored in db. can check req.headers['user-agent'], utilize in code? how tell express-session not store session sometimes?

you can utilize session middleware conditionally, based on user-agent header. simple example:

var sessionmiddleware = require('express-session')({ ...configuration here... }); app.use(function(req, res, next) { var ua = req.get('user-agent'); // if user-agent header contains string "googlebot", // skip session middleware. if (/googlebot/.test(ua)) { req.session = {}; // perhaps bit simple? homecoming next(); } homecoming sessionmiddleware(req, res, next); });

it depend on actual utilize of req.session if code above works, or if need mock req.session bit improve (for instance, if utilize of req.session methods in code, may need mock too).

node.js session express web-crawler

No comments:

Post a Comment