@hapi/cookie

Cookie-based session authentication scheme for hapi.js servers, backed by Iron-encrypted cookies.

Library
npm
v12.0.1
229stars
BSD 3-Clause License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
45/100Fair
Development Activity0
Maintenance20
Community80
Maturity60
Momentum20

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
74/100Good
Architecture78
Code Quality88
Innovation55
Learning Curve75

@hapi/cookie is the official cookie authentication plugin for the hapi.js web framework. It implements a full session-management auth scheme: after a user authenticates through some other means (typically a login form), the plugin issues a browser cookie whose contents are encrypted and signed with Iron, and every subsequent request is authenticated by decrypting and optionally re-validating that cookie.

Because it registers as a native hapi auth scheme, it plugs directly into hapi’s server.auth.strategy() API rather than acting as generic middleware, and it decorates the request object (request.cookieAuth) with set, clear, and ttl methods so route handlers can manage session state without touching cookies directly. Optional features cover keep-alive session renewal, configurable redirects for unauthenticated requests (with next URL preservation), and a per-request validate hook for checking that a session is still valid against a database or cache on every call.

What You Get

  • A registered hapi auth scheme ('cookie') usable via server.auth.strategy(name, 'cookie', options)
  • Automatic Iron encryption/signing of session cookie contents, with configurable name, domain, path, and TTL
  • A request.cookieAuth decorator exposing set(), clear(), and ttl() for managing the session from route handlers
  • Optional keepAlive support to silently refresh the cookie’s TTL on every valid request
  • Configurable redirectTo behavior for unauthenticated requests, including automatic next query-parameter appending so users land back where they started after login
  • An async validate hook to re-check session validity (e.g. against a database) on every authenticated request, with the ability to override the returned credentials

Common Use Cases

  • Server-rendered hapi.js apps that authenticate users via a login form and need browser session cookies
  • Admin dashboards and internal tools built on hapi that require login-gated routes with redirect-to-login behavior
  • Applications needing per-request session revalidation (e.g. checking a user’s account is still active) without re-issuing a new cookie each time
  • Multi-route hapi servers that need some routes to require auth (mode: 'required') and others to optionally read auth state (mode: 'try')

Under The Hood

Architecture The entire plugin lives in a single file, lib/index.js, structured as a hapi plugin object whose register hook calls server.auth.scheme('cookie', internals.implementation). internals.implementation is a closure factory: it validates the caller’s options against a Validate schema, derives settings, decorates the request object with an internals.CookieAuth instance (exposing set/clear/ttl), and returns a scheme.authenticate function built from two nested closures (validate and unauthenticated) that together decide whether a request is authenticated, revalidated via an optional user-supplied validate hook, or redirected. There is no internal layering beyond this single scheme factory plus the small CookieAuth class — the design deliberately mirrors hapi’s own auth-scheme contract rather than introducing its own abstractions, so changing hapi’s scheme interface would be the one thing that breaks this module.

Tech Stack Written in plain CommonJS JavaScript with no build step. Runtime dependencies are all hapi-ecosystem packages: @hapi/boom for HTTP-shaped errors, @hapi/bounce to distinguish expected auth failures from unexpected system errors during rethrow, @hapi/hoek for assertions and small utilities, and @hapi/validate (hapi’s Joi-derived schema validator) for options validation. Session cookies themselves are encrypted using Iron via hapi’s own server.state()/cookie jar, so this module doesn’t implement crypto directly. Dev-only dependencies are @hapi/hapi (used to spin up a real server in tests), @hapi/lab (the hapi test runner and coverage tool), @hapi/code (assertions), and @hapi/eslint-plugin.

Code Quality Tests live in a single dense test/index.js file with roughly forty it cases across five describe blocks, run through @hapi/lab -a @hapi/code -t 100 -L, which enforces both 100% statement coverage and lint-clean code as a hard test-suite requirement, backed by a GitHub Actions CI workflow. Error handling is explicit rather than swallowed: expected failures are wrapped in Boom errors, and Bounce.rethrow(err, 'system') re-throws anything that isn’t an expected auth failure instead of silently absorbing bugs. Naming follows the consistent hapi-ecosystem internals convention. There is no TypeScript and no static typing beyond what the runtime Validate schema enforces at call time.

What Makes It Unique The underlying idea — an encrypted session cookie plus a revalidation hook — is a standard pattern also seen in libraries like express-session or koa-session for other frameworks. What differentiates this package is its tight, idiomatic integration with hapi’s own primitives: it participates directly in hapi’s auth.strategy/auth.mode system rather than functioning as generic middleware, reuses hapi’s built-in Iron-backed cookie jar instead of rolling its own encryption, and allows individual routes to override redirect behavior through hapi’s per-route plugins configuration namespace.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search