Express.js 4 - use middleware for authentication before static files

Radoslav Stoyanov picture Radoslav Stoyanov · Apr 6, 2016 · Viewed 9.6k times · Source

In my express app I've set static files to be served from the /public directory with this line:

app.use(express.static(__dirname + '/public'));

Now I need to add a middleware for authentication before serving the static content and if the user is not authenticated to be redirected to a route for authentication (e.g., /login).
I'm not really sure how I have to do it. Any ideas?

Answer

christophetd picture christophetd · Apr 6, 2016

Since you didn't specify it, I'm going to assume that you already have some kind of authentication system.

In Express, the order of the middlewares in the code matters: if you want to have middleware 1 executed before middleware 2, you should place them accordingly in your code. Since express.static is a middleware, if you want authentication before serving your static files you can simply write your authentication middleware before the call to express.static

app.use(function (req, res, next) {
    if (!userAuthenticated(req)) {
        return res.redirect('/login');
    }
    next();    
});

app.use(express.static(__dirname + '/public'));

I am assuming you have a userAuthenticated function which is for instance checking if the HTTP requests contains a valid access-token.

Read more about middlewares.