How to provide a static route using Express and Nodejs

I am using Node (latest version) + Express as well as the latest version. I have 2 folders, public and protected. The protected folder should be accessible only after logging in.

I created the login system myself, now I wonder how I can protect the route to this "protected folder".

I tried to install a static route in my "secure" folder (for example, I did it with a public folder), and then check if the user is logged in, but it does not work.

This is what I thought should work ...

(...)
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'secured')));
(...)

function requireLogin(req, res, next) {
  if (req.session.loggedIn) {
    next(); // allow the next route to run
  } else {
    // require the user to log in
    res.redirect("/login"); 
  }
}

app.all("/secured/*", requireLogin, function(req, res, next) {
  next(); 

});
+5
source share
2 answers

Specify a different folder for your private statics on a separate route

app.use(express.static(path.join(__dirname, 'public')));
app.use('/private', express.static(path.join(__dirname, 'private')));

app.all('/private/*', function(req, res, next) {
  if (req.session.loggedIn) {
    next(); // allow the next route to run
  } else {
    // require the user to log in
    res.redirect("/login"); 
  }
})
+10

app.use,

-

app.use(function(req, res, next) {
  if (req.url.match(/^\/secured\//)) {
    return requireLogin(req, res, next);
  }
  next();
})
+1

All Articles