Need help with connect-ensure-login?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

439 Stars 62 Forks MIT License 18 Commits 21 Opened issues


Login session ensuring middleware for Connect and Express.

Services available


Need anything else?

Contributors list


This middleware ensures that a user is logged in. If a request is received that is unauthenticated, the request will be redirected to a login page. The URL will be saved in the session, so the user can be conveniently returned to the page that was originally requested.


$ npm install connect-ensure-login


Ensure Authentication

In this example, an application has a settings page where preferences can be configured. A user must be logged in before accessing this page.

  function(req, res) {
    res.render('settings', { user: req.user });

If a user is not logged in when attempting to access this page, the request will be redirected to

and the original request URL (
) will be saved to the session at

Log In and Return To

This middleware integrates seamlessly with Passport. Simply mount Passport's

middleware at the login route.
app.get('/login', function(req, res) {
});'/login', passport.authenticate('local', { successReturnToOrRedirect: '/', failureRedirect: '/login' }));

Upon log in, Passport will notice the

URL saved in the session and redirect the user back to

Step By Step

If the user is not logged in, the sequence of requests and responses that take place during this process can be confusing. Here is a step-by-step overview of what happens:

  1. User navigates to
    GET /settings
    • Middleware sets
    • Middleware redirects to
  2. User's browser follows redirect to
    GET /login
    • Application renders a login form (or, alternatively, offers SSO)
  3. User submits credentials to
    POST /login
    • Application verifies credentials
    • Passport reads
      and redirects to
  4. User's browser follows redirect to
    GET /settings
    • Now authenticated, application renders settings page


$ npm install --dev
$ make test

Build Status



The MIT License

Copyright (c) 2012-2013 Jared Hanson <>

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.