Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passport.deserializeUser executing a DB (sequelize) command for each HTTP request

I'm using sequelize as an ORM and passport.js (passport-local) for authentication. I noticed that every HTTP request is resulting in a separate database command. I started looking at the deserializeUser() function.

When loading a single page, this is what I get:

Executing: SELECT * FROM Users WHERE Users.id=1 LIMIT 1;

Over and over and over!

GET / 200 12ms - 780

Executing: SELECT * FROM Users WHERE Users.id=1 LIMIT 1;

Executing: SELECT * FROM Users WHERE Users.id=1 LIMIT 1;

Over and over and over!

GET /js/ui.js 304 4ms

Over and over and over!

GET /stylesheets/main.css 304 6ms

Executing: SELECT * FROM Users WHERE Users.id=1 LIMIT 1;

Over and over and over!

GET /images/logo.jpg 304 3ms

Here's how passport.deserializeUser looks:

passport.deserializeUser(function(id, done) {
    User.find(id).success(function(user) {
        console.log('Over and over and over!');
        done(null, user);
    }).error(function(err) {
        done(err, null);
    });
});

The page I'm requesting is:

index: function(req, res) {
    res.render('index', {
        title: "Welcome to EKIPLE!",
        currentUser: req.user
    });
}

Is the deserializeUser supposed to run for every image, html, css file requested? If so, is there a way of reducing the number of requests to the DB?

like image 998
vilijou Avatar asked Mar 05 '13 00:03

vilijou


1 Answers

This is a typical result of an incorrect middleware order. You should app.use (or the equivalent) the middleware which handles static resources (usually express.static or connect.static) before you app.use the Passport middleware. The same goes for other middleware which handle requests that don't require to be run through Passport.

That way, the requests for static resources will never hit the Passport middleware, so won't result in those unnecessary database-requests.

like image 169
robertklep Avatar answered Oct 14 '22 20:10

robertklep