Conditional route middleware

735 views
Skip to first unread message

Nick Poulden

unread,
May 15, 2012, 6:18:52 PM5/15/12
to expre...@googlegroups.com
I'd like to give one of my route middlewares the ability to decide which middlewares come after it based on some condition (in my case, whether a user is logged in). For example:

app.get('/',
    getSession,
    function(req, res, next) {
        if (req.session.user) {
            next([getUserOrders, getUserFavorites, renderUserHomepage]);
        }
        else {
            next([getNewProducts, getLatestDeals, renderHomepage]);
        }
    }
);

Obviously this doesn't work as expected... does anyone have any pointers how I should do this? I'm using Express 3.

tjholowaychuk

unread,
May 17, 2012, 9:49:42 AM5/17/12
to Express
you can have middleware that "wrap" other middleware, usage might look
something like:

app.get('/', authenticated(getUserOrders, getUserFavorites),
otherwise(getNewProducts, getLatestDeals), callback);

BUT in my opinion a nicer solution would be to have different routes
and rewrite req.url to point to those. for example

app.get('/', see if user is authenticated and rewrite url, then
next())

app.get('/user', getUserOrdder..., callback)

app.get('/products', ...., callback)

sorry for the short reply, i dont have much time but I hope that kinda
helps

Nick Poulden

unread,
May 21, 2012, 2:23:11 PM5/21/12
to expre...@googlegroups.com
I'll try re-writing req.url - thanks for the tip.
Reply all
Reply to author
Forward
0 new messages