{"id":17547,"library":"connect-ensure-login","title":"Connect-Ensure-Login","description":"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.","status":"abandoned","version":"0.1.1","language":"javascript","source_language":"en","source_url":"git://github.com/jaredhanson/connect-ensure-login","tags":["javascript","connect","express","auth","authn","authentication","login","session","passport"],"install":[{"cmd":"npm install connect-ensure-login","lang":"bash","label":"npm"},{"cmd":"yarn add connect-ensure-login","lang":"bash","label":"yarn"},{"cmd":"pnpm add connect-ensure-login","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for session management, especially to store and retrieve the 'returnTo' URL for post-login redirection.","package":"express-session","optional":false},{"reason":"Typically used in conjunction with this middleware to handle the actual user authentication logic and provide the `req.isAuthenticated()` method.","package":"passport","optional":false},{"reason":"This middleware is designed for Connect/Express applications, providing the HTTP server and routing context.","package":"express","optional":false}],"imports":[{"note":"The package is CommonJS-only; direct ESM imports will fail. `ensureLoggedIn` is a named export from the main module.","wrong":"import { ensureLoggedIn } from 'connect-ensure-login';","symbol":"ensureLoggedIn","correct":"const { ensureLoggedIn } = require('connect-ensure-login');"},{"note":"Also a named export. Often people try to import it from a subpath or as a default export, which is incorrect.","wrong":"import ensureLoggedOut from 'connect-ensure-login/ensureLoggedOut';","symbol":"ensureLoggedOut","correct":"const { ensureLoggedOut } = require('connect-ensure-login');"},{"note":"CommonJS module. The `require` call returns an object containing `ensureLoggedIn` and `ensureLoggedOut` as properties.","wrong":"import * as connectEnsureLogin from 'connect-ensure-login';","symbol":"connectEnsureLogin (entire module)","correct":"const connectEnsureLogin = require('connect-ensure-login');"}],"quickstart":{"code":"const express = require('express');\nconst session = require('express-session');\nconst passport = require('passport');\nconst LocalStrategy = require('passport-local').Strategy;\nconst { ensureLoggedIn } = require('connect-ensure-login');\n\nconst app = express();\n\n// Basic session setup\napp.use(session({\n  secret: 'keyboard cat', // Replace with a strong, secret key from process.env\n  resave: false,\n  saveUninitialized: false,\n  cookie: { secure: false } // Set to true if using HTTPS\n}));\n\n// Passport initialization\napp.use(passport.initialize());\napp.use(passport.session());\n\n// Dummy user storage for demonstration\nconst users = [{\n  id: 1,\n  username: 'testuser',\n  password: 'testpassword'\n}];\n\npassport.use(new LocalStrategy(\n  function(username, password, done) {\n    const user = users.find(u => u.username === username);\n    if (!user || user.password !== password) {\n      return done(null, false, { message: 'Incorrect username or password.' });\n    }\n    return done(null, user);\n  }\n));\n\npassport.serializeUser(function(user, done) {\n  done(null, user.id);\n});\n\npassport.deserializeUser(function(id, done) {\n  const user = users.find(u => u.id === id);\n  done(null, user);\n});\n\n// Routes\napp.get('/', (req, res) => {\n  res.send(`\n    <h1>Home</h1>\n    <p>Welcome, ${req.user ? req.user.username : 'Guest'}!</p>\n    <ul>\n      <li><a href=\"/login\">Login</a></li>\n      <li><a href=\"/profile\">Profile (protected)</a></li>\n      <li>${req.user ? '<a href=\"/logout\">Logout</a>' : ''}</li>\n    </ul>\n  `);\n});\n\napp.get('/login', (req, res) => {\n  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>');\n});\n\napp.post('/login',\n  passport.authenticate('local', { failureRedirect: '/login' }),\n  (req, res) => {\n    res.redirect(req.session.returnTo || '/'); // Redirect after successful login\n    delete req.session.returnTo;\n  }\n);\n\napp.get('/logout', (req, res) => {\n  req.logout((err) => {\n    if (err) { return next(err); }\n    res.redirect('/');\n  });\n});\n\n// Protected route using ensureLoggedIn\napp.get('/profile', ensureLoggedIn('/login'), (req, res) => {\n  res.send(`<h1>Profile</h1><p>Hello, ${req.user.username}!</p><a href=\"/\">Home</a>`);\n});\n\napp.listen(3000, () => {\n  console.log('Server started on http://localhost:3000');\n});\n","lang":"javascript","description":"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."},"warnings":[{"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.","message":"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.","severity":"breaking","affected_versions":"All versions"},{"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.","message":"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'.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure `express-session`, `passport.initialize()`, and `passport.session()` are all correctly configured and placed *before* `connect-ensure-login` in your middleware stack.","message":"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`.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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.","cause":"Attempting to use `require()` syntax for `connect-ensure-login` in an ECMAScript Module (ESM) file.","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Ensure `app.use(session(...))` is called *before* `app.use(ensureLoggedIn(...))`.","cause":"`express-session` middleware has not been configured or mounted before `connect-ensure-login`, so `req.session` is undefined.","error":"TypeError: Cannot read properties of undefined (reading 'returnTo')"},{"fix":"Ensure `app.use(passport.initialize())` and `app.use(passport.session())` are called *before* `app.use(ensureLoggedIn(...))`.","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.","error":"TypeError: req.isAuthenticated is not a function"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}