With Passport in an Express app, how do you write a custom API-key strategy, and what must its authenticate() method do?
answer
- subclass the base strategy
- a name plus authenticate(req, options)
- end with exactly one action
- success, fail, error, redirect, pass
basics
~10 sSubclass passport.Strategy, set this.name, and implement authenticate(req, options) so that every path ends in exactly one action: this.success(user), this.fail(challenge, status), this.error(err), this.redirect(url) or this.pass(). Then register it with passport.use().
solid answer
~40 sA custom strategy is a subclass of `passport.Strategy`, the base class Passport re-exports from `passport-strategy`. The constructor calls the base constructor, sets `this.name` (the name `passport.authenticate()` will use) and usually stores a verify callback, so the strategy only extracts credentials and the app decides who they belong to. `authenticate(req, options)` reads the header and must end each path with **exactly one** action Passport attached for this request: `this.success(user, info)`, `this.fail(challenge, status)` for missing or bad credentials (401 by default, with a string challenge sent as `WWW-Authenticate`), `this.error(err)` for an infrastructure failure, `this.redirect(url, status)` or `this.pass()`. A path that calls none leaves the request hanging. Register it with `passport.use(new ApiKeyStrategy(verify))`.
code
javascript · 10 linesconst { findClientByKey } = require('./clients');
passport.use(new ApiKeyStrategy((key, done) => {
findClientByKey(key).then((client) => done(null, client || false), done);
}));
app.get('/v1/reports',
passport.authenticate('apikey', { session: false }),
(req, res) => res.json({ client: req.user.id })
);go deeper
Recall the shape: a subclass of passport.Strategy with a name and an authenticate method, registered with passport.use like any other strategy.
Explain the five actions, why every path must end in exactly one, and why the lookup belongs in a verify callback the app supplies.
Show how fail versus error drives strategy chains and responses, why a forgotten branch hangs requests, and why per-request state on this is safe.
Decide when a custom strategy is worth owning versus a maintained package, and set the contract the team's strategies follow for challenges, statuses and errors.
## Why custom strategies are easy in Passport Every Passport strategy, from `passport-local` to `passport-openidconnect`, is the same small interface: an object with a `name` and an `authenticate(req, options)` method. When a route runs `passport.authenticate('apikey')`, Passport looks the registered instance up by name, creates a **per-request object** that inherits from it (`Object.create` on the registered instance), attaches five **action** functions bound to this request and response, and calls `authenticate`. The strategy's whole job is to call one of those actions. Nothing else about Passport changes, so a strategy you write gets `failureRedirect`, `failWithError`, the custom callback and strategy chains for free. ## The five actions | Action | Use it when | What Passport does | |---|---|---| | `this.success(user, info)` | credentials map to a user | log in (or set `req.user` with `session: false`), then `next()` | | `this.fail(challenge, status)` | credentials missing or wrong | try the next strategy; finally 401 or the given status | | `this.error(err)` | the check itself broke | `next(err)` | | `this.redirect(url, status)` | the protocol needs a browser hop | `Location` header, 302 by default | | `this.pass()` | no decision to make | `next()` without touching `req.user` | A string `challenge` passed to `fail` becomes the `WWW-Authenticate` header when the final status is 401; an object challenge carries a `message` for `failureMessage` and is not sent as a header. ## Writing the strategy The steps for an API key in an `X-API-Key` header: 1. Subclass `passport.Strategy`. Passport exports the `passport-strategy` base class under that name, and class syntax works on it. 2. In the constructor, call `super()`, set `this.name = 'apikey'`, and keep the verify callback the app passes in. 3. In `authenticate(req, options)`, read the header with `req.get('x-api-key')`. 4. No header: `this.fail('ApiKey realm="api"', 401)`. 5. Call the verify callback; map its `(err, client, info)` to `error`, `fail` or `success`, the same way `passport-local` maps `done`. 6. Register it with `passport.use(new ApiKeyStrategy(verify))` and protect routes with `passport.authenticate('apikey', { session: false })`. ```js const passport = require('passport'); class ApiKeyStrategy extends passport.Strategy { constructor(verify) { super(); this.name = 'apikey'; this._verify = verify; } authenticate(req, options) { const key = req.get('x-api-key'); if (!key) return this.fail('ApiKey realm="api"', 401); this._verify(key, (err, client, info) => { if (err) return this.error(err); if (!client) return this.fail('ApiKey realm="api", error="invalid_key"', 401); this.success(client, info); }); } } ``` Keeping lookup in a verify callback rather than inside the strategy is the convention every published strategy follows: the strategy knows the transport, the application knows its clients. ## Rules that keep a strategy correct - **Exactly one action per request.** A path that calls none, such as a forgotten `else`, never responds and the client waits for a timeout. Two actions try to answer the same response twice. - **Fail for bad input, error for broken infrastructure.** A missing or unknown key is `fail`; a key store that cannot be reached is `error`, so it reaches the error middleware instead of looking like a 401. - **Do not throw from asynchronous code.** Passport calls `authenticate` synchronously; a rejection inside an awaited lookup is not caught for you, so route it to `this.error`. - **Per-request state is safe on `this`.** Because each request works on a fresh object inheriting from the registered instance, values assigned to `this` inside `authenticate` do not leak across requests; configuration set in the constructor is shared. - **Options flow through.** The object passed to `passport.authenticate('apikey', options)` arrives as the second argument of `authenticate`, which is how strategies read per-route settings. ## Chaining with other strategies `passport.authenticate(['apikey', 'local'], { session: false })` tries the strategies in order. A `fail` moves on to the next one; `success`, `error` or `redirect` stops the chain. When all fail, Passport answers with the first status a failure carried, or 401, and collects every string challenge into `WWW-Authenticate`. That is why a strategy should `fail`, not `error`, when its credential type is simply absent: it lets the next strategy have a turn.
- What happens when a route runs passport.authenticate(['apikey', 'local']) and the request has no API key header?The API-key strategy calls `this.fail`, so Passport records the failure and tries `local`. If `local` also fails, Passport answers with the first status a failure carried, or 401, and puts each string challenge in `WWW-Authenticate`. Had the strategy called `this.error` for a missing header, the chain would have stopped with `next(err)` instead.
- When would a custom strategy call this.pass()?When it has no decision to make and wants the request to continue unchanged. Passport's built-in session strategy is the main example: it restores a user if the session holds one and calls `pass()` either way. A credential-checking strategy rarely needs it, since a missing credential should be a `fail`.
- A custom strategy must send the HTTP response itself
- Throwing an error is how a strategy rejects a bad API key
- A strategy can call both fail and success to be safe
- A missing credential should be reported with this.error
- Custom strategies cannot be combined with built-in ones in one route