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.
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:
// app/plugins/analytics.client.ts
export { default } from "@acme/analytics/plugin"
A stylesheet a plugin imports is 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:
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 } }
},
})
nameis whatdependsOnand the dev timings call the plugin; without it the name is the file name without.client/.server(analyticsforapp/plugins/analytics.client.ts).ordersorts the plugins, lower first, default0; plugins of oneorderwith nodependsOnbetween them keep the file name order, with the modules' plugins first, so the order is the same on every run.parallel: truelets the next plugin start without waiting for this one'ssetup.dependsOnmoves the plugin after the plugins it names, whatever their file names, and starts itssetuponce theirs finished, parallel or not. A name of a plugin that runs only on the other side (a.client.tsnamed 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 inHamurPluginNames, so a name no plugin has failstscas well as the start; anamethat is not a string literal is typed by its file name.hooksis registered before the first plugin'ssetupruns, 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 registeredApp plugins depend on each other: a → b → aTwo app plugins are named "a": app/plugins/a.ts and app/plugins/a.client.ts; two modules' plugins that share a file name (aruntime/plugin.tseach) are let through unless one setsnameor adependsOnnames itThe 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 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:
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:
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:
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:
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:
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:
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:
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.
| 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 |
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>.
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 shows one. The full table, with the arguments of each hook, is in ServerHooks.
| 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 has the rules and the messages.
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.
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. 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).
| 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 |
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.