Connect-Ensure-Login

raw JSON →
0.1.1 verified Thu Apr 23 auth: no javascript abandoned

Connect-Ensure-Login is a middleware designed for Connect-compatible frameworks like Express.js, primarily used to ensure a user is authenticated before accessing protected routes. If an unauthenticated request is received, the middleware redirects the user to a specified login page and stores the original requested URL in the session (via `req.session.returnTo`). After successful authentication, the application can then redirect the user back to their intended destination. The package's current stable version, 0.1.1, was released in 2013, making it over a decade old and effectively abandoned. It has no active release cadence or maintenance. Its key differentiator was its straightforward integration with Passport.js for handling common authentication flows, but its age means it lacks modern features, security updates, and compatibility with contemporary Node.js and web development practices, making it unsuitable for new projects.

error ReferenceError: require is not defined in ES module scope
cause Attempting to use `require()` syntax for `connect-ensure-login` in an ECMAScript Module (ESM) file.
fix
This package is CommonJS-only. Convert your file to CommonJS (.js without "type": "module" in package.json) or use dynamic import() for the module, if possible, although it's generally better to use modern alternatives.
error TypeError: Cannot read properties of undefined (reading 'returnTo')
cause `express-session` middleware has not been configured or mounted before `connect-ensure-login`, so `req.session` is undefined.
fix
Ensure app.use(session(...)) is called *before* app.use(ensureLoggedIn(...)).
error TypeError: req.isAuthenticated is not a function
cause `passport.initialize()` and/or `passport.session()` middleware have not been configured or mounted before `connect-ensure-login`, meaning Passport hasn't augmented the `req` object.
fix
Ensure app.use(passport.initialize()) and app.use(passport.session()) are called *before* app.use(ensureLoggedIn(...)).
breaking This package is extremely old (last update 2013) and relies on older Connect/Express paradigms (e.g., Express 3.x/4.x `req.originalUrl` behavior, older `req.isAuthenticated()` from Passport). It is not compatible with modern Node.js ESM modules or significantly newer Express versions without custom interoperability layers.
fix Migrate to a modern authentication solution, or reimplement the core logic directly with updated middleware for current Express and Passport versions. For basic login ensure, `passport.authenticate('local', { failureRedirect: '/login', keepSessionInfo: true })` combined with manual `req.session.returnTo` handling can achieve similar results.
gotcha The package is CommonJS-only (`require`). Attempting to `import` it in an ESM project will result in runtime errors like 'require is not defined in ES module scope' or 'SyntaxError: Named export 'ensureLoggedIn' not found'.
fix Ensure your project is configured for CommonJS, or use dynamic `import()` if absolutely necessary and you understand the implications of mixing module systems. The best fix is to avoid this package in modern ESM projects.
gotcha Due to its abandonment over a decade ago, `connect-ensure-login` has not received any security patches. Using it in production could expose applications to unknown vulnerabilities that have emerged in web security since 2013.
fix Avoid using this package in production. If legacy code must run, thoroughly audit its usage and consider isolating the application. Prioritize migration to actively maintained authentication solutions.
gotcha The middleware relies heavily on `req.session` and `req.isAuthenticated()`. If `express-session` is not correctly configured or `passport.initialize()` and `passport.session()` middleware are not mounted before `connect-ensure-login`, it will fail with `TypeError: Cannot read property 'returnTo' of undefined` or `TypeError: req.isAuthenticated is not a function`.
fix Ensure `express-session`, `passport.initialize()`, and `passport.session()` are all correctly configured and placed *before* `connect-ensure-login` in your middleware stack.
npm install connect-ensure-login
yarn add connect-ensure-login
pnpm add connect-ensure-login

This example demonstrates how to set up an Express application with `express-session`, `passport`, and `connect-ensure-login` to protect a route, redirect unauthenticated users to a login page, and then return them to the original protected route after successful login.

const express = require('express');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const { ensureLoggedIn } = require('connect-ensure-login');

const app = express();

// Basic session setup
app.use(session({
  secret: 'keyboard cat', // Replace with a strong, secret key from process.env
  resave: false,
  saveUninitialized: false,
  cookie: { secure: false } // Set to true if using HTTPS
}));

// Passport initialization
app.use(passport.initialize());
app.use(passport.session());

// Dummy user storage for demonstration
const users = [{
  id: 1,
  username: 'testuser',
  password: 'testpassword'
}];

passport.use(new LocalStrategy(
  function(username, password, done) {
    const user = users.find(u => u.username === username);
    if (!user || user.password !== password) {
      return done(null, false, { message: 'Incorrect username or password.' });
    }
    return done(null, user);
  }
));

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  const user = users.find(u => u.id === id);
  done(null, user);
});

// Routes
app.get('/', (req, res) => {
  res.send(`
    <h1>Home</h1>
    <p>Welcome, ${req.user ? req.user.username : 'Guest'}!</p>
    <ul>
      <li><a href="/login">Login</a></li>
      <li><a href="/profile">Profile (protected)</a></li>
      <li>${req.user ? '<a href="/logout">Logout</a>' : ''}</li>
    </ul>
  `);
});

app.get('/login', (req, res) => {
  res.send('<h1>Login</h1><form method="post" action="/login">Username: <input type="text" name="username"><br>Password: <input type="password" name="password"><br><button type="submit">Log In</button></form>');
});

app.post('/login',
  passport.authenticate('local', { failureRedirect: '/login' }),
  (req, res) => {
    res.redirect(req.session.returnTo || '/'); // Redirect after successful login
    delete req.session.returnTo;
  }
);

app.get('/logout', (req, res) => {
  req.logout((err) => {
    if (err) { return next(err); }
    res.redirect('/');
  });
});

// Protected route using ensureLoggedIn
app.get('/profile', ensureLoggedIn('/login'), (req, res) => {
  res.send(`<h1>Profile</h1><p>Hello, ${req.user.username}!</p><a href="/">Home</a>`);
});

app.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});