Skip to content

How to understand a hapi codebase

hapi favours configuration over middleware. Each route is an object with `method`, `path`, `handler` and `options` for validation, auth and caching, and cross-cutting behaviour hooks into named points of a fixed request lifecycle.

How to tell it's hapi

  • @hapi/hapi in package.json
  • server.route({ method, path, handler, options })
  • server.register(plugin) and server.ext('onPreHandler', ...)

Where things usually live

src/server.ts
Creates the server, registers plugins and auth strategies, starts it.
src/plugins/
Plugins that add routes, methods or extensions.
src/routes/
Route configuration arrays.
src/handlers/
Handler functions referenced by routes.

Conventions, not rules. Real projects rename and move things, so confirm against the repository.

Where to start reading

  1. The server file, especially server.auth.strategy and server.auth.default
  2. Plugins that register routes
  3. The route config for the endpoint

How a request moves through the code

  1. 1onRequest extensions run.
  2. 2The route is matched and authentication runs if required.
  3. 3Payload and params are validated against the route's Joi schemas.
  4. 4onPreHandler extensions run, then the handler.
  5. 5onPreResponse extensions can change the response, often for error formatting.

Questions to ask about the repository

  • Which auth strategy is the default, and which routes opt out?
  • What does each registered plugin add?
  • Which extension points are used, and for what?

What trips people up

  • A default auth strategy applies to every route unless a route sets auth: false.
  • Errors are usually Boom objects, so responses are shaped in onPreResponse, not in the handler.