Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
passport
✓ const passport = require('koa-passport');
✗ import passport from 'koa-passport';
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.
Passport
✓ const Passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
✗ import Passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';
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.
Koa
✓ const Koa = require('koa');
✗ import Koa from 'koa';
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.
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.
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const session = require('koa-session');
const passport = require('koa-passport');
const LocalStrategy = require('passport-local').Strategy;
const app = new Koa();
// Session Configuration
app.keys = ['your-secret-key']; // Replace with a strong, random key in production
app.use(session({}, app));
// Body Parser
app.use(bodyParser());
// Passport Initialization
app.use(passport.initialize());
app.use(passport.session());
// Define a local authentication strategy
passport.use(new LocalStrategy(
function(username, password, done) {
// Simulate user lookup
if (username === 'test' && password === 'password') {
return done(null, { id: 1, username: 'test' });
} else {
return done(null, false);
}
}
));
// Serialize and Deserialize user for session management
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
// Simulate user lookup by ID
done(null, { id: id, username: 'test' });
});
// Routes
app.use(async ctx => {
if (ctx.path === '/login' && ctx.method === 'POST') {
return passport.authenticate('local', async (err, user, info, status) => {
if (user) {
await ctx.login(user);
ctx.body = `Hello, ${user.username}! You are logged in.`;
} else {
ctx.status = 401;
ctx.body = 'Login failed.';
}
})(ctx);
} else if (ctx.path === '/logout') {
ctx.logout();
ctx.redirect('/');
} else if (ctx.path === '/profile') {
if (ctx.isAuthenticated()) {
ctx.body = `Welcome back, ${ctx.state.user.username}!`;
} else {
ctx.redirect('/login-page'); // Redirect to a login page
}
} else if (ctx.path === '/login-page') {
ctx.body = `
<h1>Login</h1>
<form action="/login" method="post">
<input type="text" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<button type="submit">Login</button>
</form>
`;
} else {
ctx.body = `
<h1>Home</h1>
<p>Status: ${ctx.isAuthenticated() ? 'Logged In' : 'Logged Out'}</p>
<p><a href="/login-page">Login</a></p>
<p><a href="/profile">Profile</a></p>
${ctx.isAuthenticated() ? '<p><a href="/logout">Logout</a></p>' : ''}
`;
}
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Errors
Common errors & fixes
TypeError: ctx.isAuthenticated is not a function
The `passport.initialize()` or `passport.session()` middleware has not been applied to the Koa application, or they are not in the correct order.
fixEnsure `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.
Error: Session is not configured!
Passport's session management (`passport.session()`) requires a Koa session middleware (e.g., `koa-session`) to be set up and active.
fixInstall 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. Error: Unknown authentication strategy "local"
The authentication strategy (e.g., `passport-local`, `passport-google-oauth2`) has not been properly defined and registered with Passport.
fixEnsure you have imported the necessary Passport strategy (e.g., `require('passport-local').Strategy`) and called `passport.use(new LocalStrategy(...))` before `passport.initialize()`. Audit
Dependencies
passportrequiredCore authentication library that koa-passport wraps. Major versions of koa-passport are tied to major versions of passport.
koarequiredThe web framework koa-passport is built for. Requires Koa 2.x.
koa-sessionrequiredRequired for session management when using `passport.session()`.
koa-bodyparserrequiredCommonly used for parsing request bodies, especially for login forms that submit credentials.