{"id":17446,"library":"koa-passport","title":"Koa Passport Authentication Middleware","description":"koa-passport is a middleware that integrates the popular Passport.js authentication library with the Koa web framework. It simplifies the process of adding various authentication strategies (like local username/password, OAuth, JWT) to Koa applications by exposing Passport's core functionalities directly on the Koa `ctx` object. The current stable version is 6.x, which is designed to work with Koa 2.x and Passport.js 5.x or 6.x. Its release cadence is closely tied to the major versions of its upstream `passport` and `koa` dependencies, ensuring compatibility. Key differentiators include its idiomatic Koa middleware interface, providing `ctx.login()`, `ctx.logout()`, `ctx.isAuthenticated()`, and `ctx.isUnauthenticated()` methods, which streamline user session management and status checks within Koa's async context. It requires external session management middleware like `koa-session` and typically a body parser for credential submission.","status":"active","version":"6.0.0","language":"javascript","source_language":"en","source_url":"git://github.com/rkusa/koa-passport","tags":["javascript","koa","passport","auth","authentication","authorization"],"install":[{"cmd":"npm install koa-passport","lang":"bash","label":"npm"},{"cmd":"yarn add koa-passport","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-passport","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core authentication library that koa-passport wraps. Major versions of koa-passport are tied to major versions of passport.","package":"passport","optional":false},{"reason":"The web framework koa-passport is built for. Requires Koa 2.x.","package":"koa","optional":false},{"reason":"Required for session management when using `passport.session()`.","package":"koa-session","optional":false},{"reason":"Commonly used for parsing request bodies, especially for login forms that submit credentials.","package":"koa-bodyparser"}],"imports":[{"note":"The official documentation and examples for koa-passport@6.x primarily use CommonJS `require`. While modern Koa often uses ESM, ensure your project setup supports CommonJS for this package, or use a tool like `ts-node/register` if mixing.","wrong":"import passport from 'koa-passport';","symbol":"passport","correct":"const passport = require('koa-passport');"},{"note":"You typically need to import the core `passport` library separately to configure strategies (e.g., `passport-local`, `passport-google-oauth2`). Stick to CommonJS `require` for consistency with `koa-passport` unless your environment is fully configured for ESM interoperability.","wrong":"import Passport from 'passport';\nimport { Strategy as LocalStrategy } from 'passport-local';","symbol":"Passport","correct":"const Passport = require('passport');\nconst LocalStrategy = require('passport-local').Strategy;"},{"note":"While Koa itself supports both CJS and ESM, the `koa-passport` examples provided use CommonJS `require`. For seamless integration, using `require` for Koa might be necessary depending on your module resolution settings if not transpiling.","wrong":"import Koa from 'koa';","symbol":"Koa","correct":"const Koa = require('koa');"}],"quickstart":{"code":"const Koa = require('koa');\nconst bodyParser = require('koa-bodyparser');\nconst session = require('koa-session');\nconst passport = require('koa-passport');\nconst LocalStrategy = require('passport-local').Strategy;\n\nconst app = new Koa();\n\n// Session Configuration\napp.keys = ['your-secret-key']; // Replace with a strong, random key in production\napp.use(session({}, app));\n\n// Body Parser\napp.use(bodyParser());\n\n// Passport Initialization\napp.use(passport.initialize());\napp.use(passport.session());\n\n// Define a local authentication strategy\npassport.use(new LocalStrategy(\n  function(username, password, done) {\n    // Simulate user lookup\n    if (username === 'test' && password === 'password') {\n      return done(null, { id: 1, username: 'test' });\n    } else {\n      return done(null, false);\n    }\n  }\n));\n\n// Serialize and Deserialize user for session management\npassport.serializeUser(function(user, done) {\n  done(null, user.id);\n});\n\npassport.deserializeUser(function(id, done) {\n  // Simulate user lookup by ID\n  done(null, { id: id, username: 'test' });\n});\n\n// Routes\napp.use(async ctx => {\n  if (ctx.path === '/login' && ctx.method === 'POST') {\n    return passport.authenticate('local', async (err, user, info, status) => {\n      if (user) {\n        await ctx.login(user);\n        ctx.body = `Hello, ${user.username}! You are logged in.`;\n      } else {\n        ctx.status = 401;\n        ctx.body = 'Login failed.';\n      }\n    })(ctx);\n  } else if (ctx.path === '/logout') {\n    ctx.logout();\n    ctx.redirect('/');\n  } else if (ctx.path === '/profile') {\n    if (ctx.isAuthenticated()) {\n      ctx.body = `Welcome back, ${ctx.state.user.username}!`;\n    } else {\n      ctx.redirect('/login-page'); // Redirect to a login page\n    }\n  } else if (ctx.path === '/login-page') {\n    ctx.body = `\n      <h1>Login</h1>\n      <form action=\"/login\" method=\"post\">\n        <input type=\"text\" name=\"username\" placeholder=\"username\" />\n        <input type=\"password\" name=\"password\" placeholder=\"password\" />\n        <button type=\"submit\">Login</button>\n      </form>\n    `;\n  } else {\n    ctx.body = `\n      <h1>Home</h1>\n      <p>Status: ${ctx.isAuthenticated() ? 'Logged In' : 'Logged Out'}</p>\n      <p><a href=\"/login-page\">Login</a></p>\n      <p><a href=\"/profile\">Profile</a></p>\n      ${ctx.isAuthenticated() ? '<p><a href=\"/logout\">Logout</a></p>' : ''}\n    `;\n  }\n});\n\napp.listen(3000, () => console.log('Server running on http://localhost:3000'));","lang":"javascript","description":"This example sets up a basic Koa application with `koa-passport` using a local authentication strategy. It demonstrates session management, body parsing, user serialization/deserialization, and defines routes for login, logout, and a protected profile page. It also includes a basic HTML login form."},"warnings":[{"fix":"Always check the compatibility table in the `koa-passport` README when upgrading. For version 6.x, ensure `passport` is 5.x or 6.x and `koa` is 2.x.","message":"`koa-passport` major versions are tightly coupled with `passport` and `koa` major versions. Upgrading one without the others can lead to incompatibility issues.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Update `ctx.logout()` calls to await the returned promise and remove any callback arguments.","message":"The `logout` function's signature changed in `koa-passport` 6.0.0 from a callback-based `(options, callback) => void` to a Promise-based `(options) => Promise<void>`.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Update code accessing `ctx.passport` to use `ctx.state` instead for user and passport-related state. Review custom authentication callbacks as their arguments also changed.","message":"In `koa-passport` v3.0.0, `ctx.passport` was removed, and state variables like `_passport` and `user` were moved to `ctx.state`. Passport no longer monkey patches `http.IncomingMessage` directly.","severity":"breaking","affected_versions":">=3.0.0 <4.0.0"},{"fix":"Ensure `koa-session` and `koa-bodyparser` (or equivalent middleware) are properly configured and `app.use()`'d *before* `passport.initialize()` and `passport.session()`.","message":"`koa-passport` relies on external session middleware (like `koa-session`) and typically a body parser (like `koa-bodyparser`) to function correctly, especially for session-based authentication and handling login form submissions.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `app.use(passport.initialize())` and `app.use(passport.session())` are called on your Koa app after session middleware and before any routes that use Passport's context methods.","cause":"The `passport.initialize()` or `passport.session()` middleware has not been applied to the Koa application, or they are not in the correct order.","error":"TypeError: ctx.isAuthenticated is not a function"},{"fix":"Install and configure `koa-session` (or a similar session middleware) by calling `app.use(session({}, app))` before `app.use(passport.session())`. Remember to set `app.keys` for session signing.","cause":"Passport's session management (`passport.session()`) requires a Koa session middleware (e.g., `koa-session`) to be set up and active.","error":"Error: Session is not configured!"},{"fix":"Ensure you have imported the necessary Passport strategy (e.g., `require('passport-local').Strategy`) and called `passport.use(new LocalStrategy(...))` before `passport.initialize()`.","cause":"The authentication strategy (e.g., `passport-local`, `passport-google-oauth2`) has not been properly defined and registered with Passport.","error":"Error: Unknown authentication strategy \"local\""}],"ecosystem":"npm","meta_description":null}