# Plugins and hooks

Hamur has three places to run your code at a fixed point: a plugin, a hook and a handler that wraps an answer. App plugins run when the app starts, in the browser and on the server. Server plugins run once when the server starts. Build hooks run while Hamur builds, and are for modules and the config. Each side has its own hook table below; the full signature of every hook is in its reference page.

## App plugins

A file in `app/plugins/` runs when the app starts, on the server for each request and in the browser at load. Use `dependsOn` when one plugin needs another, and `order` to move one early or late; a number in the file name does not order anything, and a file such as `01.auth.ts` fails the scan with `app/plugins/01.auth.ts: a plugin is ordered by order or dependsOn in definePlugin, not by a number in its file name; rename it auth.ts`. A `.client.ts` or `.server.ts` ending limits the side. The plugin gets the app context and may return `provide`, which becomes properties of the app context and is available as `useApp()` in the adapter. Typegen types the provided keys from the plugin files, so a misspelt key fails `tsc`.

````ts [plugins/app-plugin.ts]
import { definePlugin } from "hamur/app"

export default definePlugin((app) => {
  app.hooks.hook("page:finish", (route) => {
    console.log(`rendered ${route.path}`)
  })
  return { provide: { track: (event: string) => console.log(`track ${event}`) } }
})
````

A plugin from a package is a one-line file that re-exports it. The file gives it its name and its side, as for a plugin written in the app:

```ts
// app/plugins/analytics.client.ts
export { default } from "@acme/analytics/plugin"
```

A stylesheet a plugin imports is [global CSS](/styling#global-css), linked on every page. The config has no `plugins` list; a config that sets one fails when it loads with `plugins was removed; put the plugin in app/plugins/ or re-export it there (export { default } from "@acme/analytics/plugin")`. A module adds a plugin with `addAppPlugin`.

A plugin may also be an object, which names it, orders it and runs it beside the others:

````ts [plugins/app-plugin-object.ts]
import { definePlugin } from "hamur/app"

const sent: string[] = []
const track = (event: string) => void sent.push(event)

export default definePlugin({
  name: "analytics",
  order: -10,
  parallel: true,
  dependsOn: ["consent"],
  hooks: { "page:finish": (route) => track(`view ${route.path}`) },
  async setup() {
    await fetch("/tracker.js")
    return { provide: { track } }
  },
})
````

- `name` is what `dependsOn` and the dev timings call the plugin; without it the name is the file name without `.client`/`.server` (`analytics` for `app/plugins/analytics.client.ts`).
- `order` sorts the plugins, lower first, default `0`; plugins of one `order` with no `dependsOn` between them keep the file name order, with the modules' plugins first, so the order is the same on every run.
- `parallel: true` lets the next plugin start without waiting for this one's `setup`.
- `dependsOn` moves the plugin after the plugins it names, whatever their file names, and starts its `setup` once theirs finished, parallel or not. A name of a plugin that runs only on the other side (a `.client.ts` named on the server) is skipped on this side. A plugin sees what a parallel plugin provides only when it depends on it. Typegen lists every plugin's name in `HamurPluginNames`, so a name no plugin has fails `tsc` as well as the start; a `name` that is not a string literal is typed by its file name.
- `hooks` is registered before the first plugin's `setup` runs, so the hook sees everything the plugins do.

Every plugin has finished before `app:created`. A plugin that throws, parallel or not, fails the start at once and no plugin starts after it; plugins that failed together are thrown as one `AggregateError`. These fail at start:

- `App plugin "b" depends on "x", which is not registered`
- `App plugins depend on each other: a → b → a`
- `Two app plugins are named "a": app/plugins/a.ts and app/plugins/a.client.ts`; two modules' plugins that share a file name (a `runtime/plugin.ts` each) are let through unless one sets `name` or a `dependsOn` names it
- `The default export of app plugin "x" is not a plugin; wrap it in definePlugin()`

A `provide` key that the context already has is an error. The hooks a plugin can register are in [App hooks](#app-hooks).

### App setup per adapter

The `app:adapter` hook is where a plugin sets up the UI library's app, as Vike's `onCreateApp` does. It gets `(instance, app)`: `instance` is the library's app object and `app` is the app context. It runs before the first render, on the server and in the browser, once per app context and instance. Vue and Angular have an app object: in Vue `instance` is Vue's `App`, and in Angular it is an `AngularSetup`, whose `providers` list takes Angular providers. In React, Preact, Svelte, Solid and html, `instance` is `null`; use the hook for what belongs to the app context.

React:

````ts [app-setup/react.ts]
import { definePlugin } from "hamur/app"

export default definePlugin({
  hooks: {
    "app:adapter": (instance, app) => {
      if (instance === null) app.hooks.hook("app:mounted", () => console.log("mounted"))
    },
  },
})
````

Vue calls `app.use`, here with a plugin object; pinia and vue-router style plugins install the same way:

````ts [app-setup/vue.ts]
import { definePlugin } from "hamur/app"
import type { App, Plugin } from "vue"

const theme: Plugin = {
  install(app) {
    app.provide("theme", "dark")
  },
}

export default definePlugin({
  hooks: {
    "app:adapter": (instance) => {
      ;(instance as App).use(theme)
    },
  },
})
````

Preact:

````ts [app-setup/preact.ts]
import { definePlugin } from "hamur/app"

export default definePlugin({
  hooks: {
    "app:adapter": (instance, app) => {
      if (instance === null) app.hooks.hook("app:mounted", () => console.log("mounted"))
    },
  },
})
````

Svelte:

````ts [app-setup/svelte.ts]
import { definePlugin } from "hamur/app"

export default definePlugin({
  hooks: {
    "app:adapter": (instance, app) => {
      if (instance === null) app.hooks.hook("app:mounted", () => console.log("mounted"))
    },
  },
})
````

Solid:

````ts [app-setup/solid.ts]
import { definePlugin } from "hamur/app"

export default definePlugin({
  hooks: {
    "app:adapter": (instance, app) => {
      if (instance === null) app.hooks.hook("app:mounted", () => console.log("mounted"))
    },
  },
})
````

html:

````ts [app-setup/html.ts]
import { definePlugin } from "hamur/app"

export default definePlugin({
  hooks: {
    "app:adapter": (instance, app) => {
      if (instance === null) app.hooks.hook("app:mounted", () => console.log("mounted"))
    },
  },
})
````

Angular pushes providers into the `AngularSetup`; a component reads them with `inject`:

````ts [angular/app-providers.ts]
import { InjectionToken } from "@angular/core"
import type { AngularSetup } from "@hamur/adapter-angular"
import { definePlugin } from "hamur/app"

export const API_URL = new InjectionToken<string>("API_URL")

export default definePlugin({
  hooks: {
    "app:adapter": (instance) => {
      ;(instance as AngularSetup).providers.push({ provide: API_URL, useValue: "https://api.example.com" })
    },
  },
})
````

## App hooks

`app.hooks` is a `Hooks<AppHooks>`. A plugin registers on it with `app.hooks.hook(name, fn)` or with the `hooks` of an object plugin, and a component with `useRuntimeHook`. The signature of each hook is in [`AppHooks`](/api-reference/app#apphooks-hooks-pagehookinfo-beforenavigateinfo).

| Hook                                                                                                                                     | Runs                                                                                                                             |
| ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `app:created`                                                                                                                            | after every plugin ran                                                                                                           |
| `app:adapter`                                                                                                                            | before the first render, with the UI library's app instance: Vue's `App`, Angular's `AngularSetup`, `null` in the other adapters |
| `app:beforeMount`                                                                                                                        | in the browser, once, before the first `hydrate` or `mount`                                                                      |
| `app:mounted`                                                                                                                            | in the browser, after the first render                                                                                           |
| `app:rendered`                                                                                                                           | on the server, after the adapter rendered and before the document is joined                                                      |
| `app:error`, `app:error:cleared`, `app:chunkError`, `app:update`                                                                         | in the browser: an error reached the navigator, an error was cleared, a chunk failed to load twice, a newer build exists         |
| `app:vital`                                                                                                                              | in the browser, for each web vital once it is final; see [Web vitals](/observability#web-vitals-in-the-page)                     |
| `app:data:refresh`                                                                                                                       | before `refreshData(keys)` or `router.refresh()` runs the loads again                                                            |
| `app:ssrLogs`                                                                                                                            | in the browser under `hamur dev` only                                                                                            |
| `page:beforeNavigate`, `page:start`, `page:loading:start`, `page:loading:end`, `page:data`, `page:finish`, `page:rendered`, `page:error` | around a page render or a navigation                                                                                             |
| `page:transition:finish`, `page:view-transition:start`                                                                                   | around a page, layout or view transition in the browser                                                                          |
| `link:prefetch`                                                                                                                          | in the browser, for each prefetch that starts a fetch                                                                            |

### `useRuntimeHook` and `onAppReady`

A plugin lives as long as the app; a component does not. `useRuntimeHook(name, fn)` registers `fn` on `useApp().hooks` and removes it when the component, page or effect that called it goes away, so a hook is not called after its page is gone. `onAppReady(fn)` runs `fn` once in the browser after `app:mounted`, when the browser is idle, and does nothing on the server. Both come from the adapter of your library; the signatures and the per-library cleanup are in [`@hamur/adapter-<library>`](/api-reference/adapters#useruntimehook).

````ts [plugins/runtime-hook.ts]
import { onAppReady, useRuntimeHook } from "@hamur/adapter-html"

export default function Checkout(): string {
  useRuntimeHook("page:finish", (route) => console.log(`left ${route.path}`))
  onAppReady(() => void fetch("/api/warm"))
  return `<h1>Checkout</h1>`
}
````

## Server plugins and hooks

A server plugin is `definePlugin(fn)` of `hamur/server`, listed in `plugins` of `defineServer`. It runs once when the server starts and gets `{ hooks, runtimeConfig, log, addLogSink, addSpanExporter, addMetricExporter }`; [Server](/server#plugins-and-hooks) shows one. The full table, with the arguments of each hook, is in [`ServerHooks`](/api-reference/server#defineplugin-serverplugin-hamurserver-serverhooks-errorcontext-errorphase).

| Hook                                                                              | Runs                                                                         |
| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| `request`, `beforeResponse`, `afterResponse`                                      | around every request                                                         |
| `error`                                                                           | for every error the server answers, with the raw error and an `ErrorContext` |
| `function:error`                                                                  | for the error of a handler, before it is masked                              |
| `render:html`, `render:stream`, `render:response`                                 | on a page document: its parts, its stream, its `Response`                    |
| `fetch:request`, `fetch:response`                                                 | around every server-side `$fetch`                                            |
| `client:report`                                                                   | for each accepted report the browser sent                                    |
| `task:error`                                                                      | when a task run that nobody awaits failed                                    |
| `syncedState:access`                                                              | before each read or write of `server.syncedState`                            |
| `cloudflare:scheduled`, `cloudflare:queue`, `cloudflare:email`, `cloudflare:tail` | on the cloudflare preset, for those events                                   |
| `close`                                                                           | when the server shuts down                                                   |

### Change the error answer and the page answer

`error` and `render` of `defineServer` are single handlers, not hooks: they can replace the answer. `defineErrorHandler` runs for every error the server answers, after the `error` hooks; `defineRenderHandler` wraps every page answer. A module's door and a layer's door may set them too: the app's runs first, then each layer's, then each module's, and `next()` or `render()` reaches the following one. [Errors](/errors#changing-the-error-answer) has the rules and the messages.

````ts [plugins/server-door.ts]
import { createError, defineErrorHandler, defineRenderHandler, defineServer, definePlugin } from "hamur/server"

const logging = definePlugin(({ hooks, log }) => {
  hooks.hook("request", (event) => log.debug(`request ${event.url.pathname}`))
  hooks.hook("error", (error) => log.error(String(error)))
})

class MissingError extends Error {}

export default defineServer({
  plugins: [logging],
  error: defineErrorHandler((error, _event, { next }) =>
    error instanceof MissingError ? next(createError({ status: 404 })) : undefined,
  ),
  render: defineRenderHandler(async (_event, { render }) => {
    const response = await render()
    response.headers.set("x-rendered-by", "hamur")
    return response
  }),
})
````

Errors a handler logs yourself go through `captureError(event, error)`, and `defineLogSink` makes a log sink for `setLogSink`; both are in the [server reference](/api-reference/server).

## Build hooks

Build hooks are for `hooks` in the config and for a module's `hooks` or `useHamur().hooks`. They are typed by `HamurHooks`, so a wrong name or signature is a type error; the signatures are in [`HamurHooks`](/api-reference/hamur#hamurhooks-tsconfigfile). A kit call that adds pages, layouts, route middleware, app plugins, a server door, templates, type templates or imports works until `build:before`; after it, it throws and names the hook ([The kit](/modules#the-kit)).

| Hook                                                   | Runs                                                                                                          |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
| `config:resolved`                                      | once the config is merged; only the config's `hooks` can use it, a module is set up later                     |
| `modules:done`                                         | after every module's `setup`                                                                                  |
| `pages:extend`, `server:extend`, `templates:extend`    | with the routes, the server routes and the templates, to change them; a kit call in one adds to the same list |
| `prepare:types`                                        | with the tsconfig of each context, before they are written                                                    |
| `ready`                                                | once, after modules, the first scan and typegen; it only reads                                                |
| `build:before`                                         | before the client build                                                                                       |
| `build:client:config`, `build:server:config`           | with the `Bun.build` config of each side                                                                      |
| `build:manifest`                                       | `hamur build` only: the client manifest, before the server build reads it                                     |
| `build:done`                                           | after the build, with its outputs                                                                             |
| `build:error`                                          | a build failed or a hook from `build:before` to `prerender:done` threw                                        |
| `prerender:routes`, `prerender:page`, `prerender:done` | which paths to prerender, each page before it is written, the list of written files                           |
| `dev:ready`, `dev:change`, `restart`                   | `hamur dev`: it serves, a watched file changed, a module asks for a new process                               |
| `markdown:highlight`                                   | once per code block of a Markdown page                                                                        |
| `close`                                                | at the end of the command                                                                                     |

````ts [plugins/build-hooks.ts]
import { defineConfig } from "hamur"

export default defineConfig({
  framework: "html",
  hooks: {
    "pages:extend": (routes) => {
      for (const route of routes) console.log(route.path)
    },
    "prerender:routes": (routes) => void routes.add("/offline"),
    "build:done": ({ report }) => console.log(report),
  },
})
````

A module registers hooks with `hooks` of `defineModule`, which are set just before its `setup`, or with `hamur.hooks.hook(name, fn)` inside `setup`. A module cannot register `config:resolved`; it has run by then.
