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

1

11

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?

Quadri answered 5/3, 2013 at 0:3 Comment(0)
E
23

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.

Euplastic answered 5/3, 2013 at 7:50 Comment(1)
Great solution, I have a variation of this problem and posted a question in here #34278248Alasdair

© 2022 - 2024 — McMap. All rights reserved.