passport-headerapikey
A lightweight Passport.js strategy for authenticating requests with a header-based API key.
Repository Health
Technical Analysis
passport-headerapikey is a Passport.js authentication strategy that verifies requests using an API key sent in an HTTP header, rather than in the request body or query string. It integrates with any Connect- or Express-style middleware stack the same way other Passport strategies do, letting you drop header-based API key auth into an existing authentication pipeline alongside other strategies.
The strategy is configurable via a header name and an optional prefix (for example, an Authorization header with a Bearer or Api-Key prefix), and it supports Passport’s passReqToCallback option so verify callbacks can access the full request. It ships with a small, TypeScript-first API surface and no built-in database logic - verification is left entirely to a user-supplied verify callback, keeping the library focused solely on extracting and validating the header value.
What You Get
- HeaderAPIKeyStrategy class - A Passport-compatible strategy class exported as both
defaultandHeaderAPIKeyStrategyfor drop-inpassport.use()registration. - Configurable header + prefix - Specify any header name (defaults to
X-Api-Key) and an optional prefix likeBearerorApi-Keythat the strategy strips before verification. - passReqToCallback support - Optionally receive the full Express
Requestobject in your verify callback for request-aware validation logic. - BadRequestError type - A dedicated error class thrown for missing or malformed API keys, distinguishing client input errors from verify-callback failures.
Common Use Cases
- Machine-to-machine REST APIs - Services that authenticate other services or scripts using a static API key instead of session cookies or OAuth tokens.
- Legacy API key migration - Teams adding Passport-based auth to an existing API that already issues API keys, without rewriting the API key format.
- Multi-strategy Passport apps - Applications that already use Passport for session-based login and want to add a parallel API-key path for programmatic clients.
Under The Hood
Architecture
passport-headerapikey exposes a single Strategy class (src/Strategy.ts) extending passport-strategy’s base Strategy, re-exported from src/index.ts as both the default and the named HeaderAPIKeyStrategy export. The constructor accepts a header/prefix configuration object, a passReqToCallback flag, and a verify function; authenticate() reads the configured header via lodash’s _.get, validates an optional prefix, and calls into the caller-supplied verify callback through a small internal verified continuation that maps to Passport’s success/fail/error lifecycle methods. A dedicated BadRequestError class (src/errors/BadRequestError.ts) carries validation failures. There is no internal layering beyond this - the entire library is one strategy class plus one error type, so any change to the constructor signature or the authenticate contract would break every consumer directly, with no adapter layer to absorb it.
Tech Stack
The library is written in TypeScript (tsconfig.json, tslint.json) and compiles to a lib/ directory that is the sole published artifact (files: ["lib/"], main/types pointing into lib/). Runtime dependencies are limited to lodash for header lookups and prefix checks and passport-strategy as the base class; express’s Request type is used only for typing, not as a runtime dependency. The devDependency set (mocha, expect.js, sinon, an older TypeScript compiler) reflects a stack that hasn’t been refreshed since the project’s most recent activity, with no visible CI configuration or modern bundler in the shallow clone.
Code Quality Unit tests live under test/unit/ (StrategyTest.ts, BadRequestErrorTest.ts) and use mocha with expect.js assertions and sinon stubs/spies to exercise constructor defaults and every authenticate() branch - missing key, wrong prefix, verify error, verify failure, and verify success. Error handling is explicit and typed via BadRequestError rather than raw throws or swallowed failures. Naming is consistent and the public API is fully typed, though the project relies on the now-deprecated tslint rather than ESLint, and no CI workflow file was found in the cloned tree.
API Design
The public surface is a single constructor taking a header/prefix config object, a positional boolean (passReqToCallback), and a verify callback - mirroring the shape of other Passport strategy packages, which keeps the learning curve low for anyone already using Passport. The positional boolean argument is less self-documenting than a named option would be, and configuration is a plain object without runtime defaults enforcement beyond the constructor’s manual fallback logic. The README supplies a complete, copy-pasteable usage example, and TypeScript types stand in for additional API documentation.
Used by 6 apps in this directory
Bigcapital
Invoicing Finance
Self-hostable double-entry accounting platform with invoicing, inventory, multi-currency, and real-time financial reporting for small and medium businesses.
Ghostfolio
Invoicing Finance
Track your stocks, ETFs, and crypto with a privacy-first, self-hostable wealth management platform built for data-driven investors.
Laudspeaker
Marketing · Automation
Open-source customer engagement platform for building visual, event-triggered messaging journeys across email, SMS, push, in-app, and webhooks.
Lightdash
Analytics · Data Engineering
The open-source Looker alternative that turns your dbt project's metrics and dimensions into governed, self-serve charts and dashboards — no license key required.
Novu
Developer Tools
Open-source communication infrastructure that connects your products and AI agents to every channel your users live on — Inbox, Email, SMS, Push, Chat, and more.
Swetrix
Analytics
Privacy-first, cookieless web analytics with error tracking, session replays, and performance monitoring — self-host or use Cloud.