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?
Depends on what kind of authentication you are looking for, but if you just want some login-feature, this is what you need: http://passportjs.org/
It has support for local login strategies, as well as a whole bunch of 3rd party strategies like facebook, twitter, etc.
If you need something else, simpler or self-made, just write a middleware to use before you declare the static endpoint, and call next() if everything checks out, and res.redirect if user needs to retry.
Check out Passport.
Passport has many authentication strategies.
Here's an example with basic HTTP authentication:
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 toexpress.static
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.