Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 235
Radoslav Stoyanov Avatar asked Dec 06 '22 18:12

Radoslav Stoyanov


1 Answers

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.

like image 78
christophetd Avatar answered Jan 03 '23 21:01

christophetd