Photo Credit: Cayusa

Tutorial: Require authentication for Express.js apps

Matthew Nuzum —  — Leave a comment

It’s quite common to create an app where you want to protect numerous pages. It’s not difficult to check for req.user and force the user to a login page, but code duplication is not a good idea. Fortunately, it’s quite easy to write a middleware that will require authentication for a whole set or URLs.

First, we’ll set some assumptions: You’re using Express 4.x, you’re using router (is there any other way?) and you’re probably using Passport. I don’t think Passport is required for this solution, but it’s the only option I’ve tested with. Let’s assume that you’ve got a homepage that does not require authentication but the rest of your site, other than the login/logout/register pages, require authentication.

In my app.js file I’ve got routes specified like this:

app.use('/', routes);
app.use('/myapp/', myapp);
app.use('/login/', login);

In this case, myapp is the file where I’ve defined my routes for the part of my app that needs authentication. To specify a middleware for all routes in that file I just create a route like this:

router.use(function(req, res, next) {
  if(!req.user) {
    res.redirect('/login');
  }
  next();
});

There’s no magic here, but let’s walk through it. First, note that I didn’t specify a URL for this route. In my case, I specified this as the first route in the file, but I’m not certain that’s necessary. Here are the docs for router.use.

The guts of the app simply check if the user is logged in by checking the existence of req.user. It is entirely possible to get more complicated here, for example, you could check for a certain role, or check that their profile has been completed. If req.user is falsy then I redirect to the login page. In my case, this is a page I created that lists the Passport strategies that are available, such as Twitter or Facebook.

If the user is logged in, it’s important to call the next() method to ensure that the next matching route is run.

By the way, if you are trying to setup Passport or any authentication and the login works but when you visit any other page you’re no longer logged in, check that you have session middleware installed! This is no longer included by default, you have to activate it manually.

If it helped, please share!Tweet about this on TwitterShare on FacebookShare on LinkedInShare on Google+

Matthew Nuzum

Posts Twitter Facebook

Web guy, big thinker, loves to talk and write. Front end web, mobile and UX developer for John Deere ISG. My projects: @dsmwebgeeks @tekrs @squaretap ✝