@ogygia/core
Server hooks
A plugin's server half is defineServer({ … }), run inside ogygia.handle(). It sets up once, then gets a stage of every request in a fixed order: around it, before routing, before a page renders, on the response and at the end. Shared hooks let plugins call each other.
A plugin’s server half is the module its server location names. Its default export is defineServer({ … }) from @ogygia/core/plugin. The build imports it into the server bundle, and ogygia.handle() runs it: setup once when the server starts, then each request’s stages in order, for every listed plugin in plugin order.
defineServer<Options, State> only types the object: Options is what the plugin’s options hold, and State what state() makes. Every hook is optional.
import { defineServer } from '@ogygia/core/plugin';
interface Options {
header: string;
}
interface State {
started: number;
}
export default defineServer<Options, State>({
setup(app) {
app.warn(`stamping with ${app.options.header}`);
},
state: () => ({ started: performance.now() }),
response(ctx, res) {
const ms = (performance.now() - ctx.state.started).toFixed(
1
);
res.headers.set(ctx.options.header, `${ms}ms`);
}
});Request stages
| Hook | Kind | When it runs | Its return value |
|---|---|---|---|
setup(app) | once | When the handle module loads, before any request. | Ignored. |
state() | per request | When a request’s contexts are made. | This plugin’s ctx.state for the request. |
handle(ctx, next) | around | Around the whole request, like Kit’s handle. | The response. |
request(ctx) | first | Every request, before the split into pages and region requests. | A Response answers the request; later plugins and ogygia don’t run. |
page(ctx) | first | A request Kit is about to resolve, before Kit runs. | A Response answers it; Kit never runs. |
response(ctx, res) | sequential | The response Kit resolved, before it streams out. | A Response replaces it for the plugins after, and goes out as they leave it. |
done(ctx) | parallel | The request’s end, always. | Work that must finish, as a promise. |
pass(event) | lookup | Whenever ogygia needs to know whether the app runs its own pass over the HTML. | An HtmlPass, or nothing. |
A throw in setup, handle, request, page or response isn’t caught by ogygia: it fails the server start, or the request, as a throw in Kit’s own handle would. Only done and the shared hooks are guarded.
setup
setup(app) runs once when the server’s handle module loads, with app, the server process as this plugin sees it. Set up module-level things here. On the dev server, an edit that runs hooks.server.ts again starts the plugins again: the earlier run’s shared hooks leave first, and setup runs once more.
state
state() makes a fresh value for each request, handed back as ctx.state in every later stage of that request. Use it for what one stage learns and another needs, such as a start time or a cache key, instead of a module-level map.
handle
handle(ctx, next) wraps the whole request, the way Kit’s handle does. next() runs the rest (the later plugins’ handle, then ogygia) and returns its response. Return it, change it, or answer without calling next() at all. The first plugin’s handle is the outermost.
Its ctx is smaller than the other stages’: event, options and app, since nothing about the request is decided yet. next(options) passes Kit resolve() options. A transformPageChunk there runs after ogygia’s own, so it sees the finished document. Most plugins want the stages below. handle is for what must wrap everything, such as a profiler timing the request or a plugin serving its own pages.
request
request(ctx) runs on every request that reaches ogygia’s handle: pages, endpoints, data requests, remote function calls, and the region endpoint that server islands and live regions fetch from. It runs before ogygia decides which of those it is, so whatever it sets up is there for all of them. @ogygia/flags decides a request’s flags here. The first plugin to return a Response answers the request.
page
page(ctx) runs before Kit resolves a request, for every request except the region endpoint and the page lookups a server island makes. That includes +server endpoints, Kit’s __data.json requests and remote function calls, so check what you need: ctx.forPage is true for a request that renders on behalf of a page it isn’t, such as a remote function call, and event.isDataRequest marks a data request. By this stage ctx.facts.private and ctx.facts.answerForm are set.
The first plugin to return a Response answers, and Kit, the loads and Svelte never run. That’s how postrender serves a stored page. A plugin that may store the render it lets through says so before it, by setting ctx.facts.storable.
response
response(ctx, res) gets the response Kit resolved, before it streams out. Each plugin sees what the one before it left. Return nothing to keep it, or a new Response to replace it. A replaced response is final: it goes out as the plugins leave it, without the streamed tail that ogygia adds for load promises, so replace a page only with a copy that’s complete. ctx.facts.streamed says whether the page has such a tail.
res is Kit’s own response, so its headers can be set in place, as the first example does. A response that came from fetch() has headers you can’t change: make a new Response around its body instead.
done
done(ctx) runs at the request’s end, always: an answered request, a failed one, and a streamed one too, when ogygia’s handle returned its response, possibly before a streamed body finished. Every plugin’s done runs, in order. It must not throw, and one that does is reported with plugin_hook_failed without stopping the others.
Return a promise for work that must finish, such as a send to a log service. The response never waits for it. When the platform keeps a request alive past its response (a waitUntil at event.platform.context or event.platform.ctx), the work is handed to it. Otherwise it runs on in the server process. A rejected promise is reported the same way, and never fails the request. For work started outside done, use app.keepAlive.
pass
pass(event) is for a plugin that runs the app’s own pass over the HTML ogygia sends, such as a server render of web components. It’s a lookup, synchronous and cheap: return an HtmlPass for this request, or nothing. The first plugin that answers owns the pass.
An HtmlPass has two methods. document(html, page) gets a page one chunk at a time, in order, as Kit hands them out. page says whether Kit hydrates it (csr), whether the router fetched it to render as an answer (answer), whether the chunk holds </head> (head) or </body> (body), and whether it’s the last (done). It returns the chunk’s HTML, plus HTML to put before </head> and before </body>, read when the chunk holds those tags. region(html) gets each region answer (a hole, a batch, a lake remount) fully assembled, and returns it changed. @ogygia/rewrite is built on it.
import { defineServer } from '@ogygia/core/plugin';
export default defineServer({
async handle({ event }, next) {
if (event.url.pathname === '/__stamp')
return new Response('ok');
return next({
transformPageChunk: ({ html }) =>
html.replace('</body>', '<!-- stamped --></body>')
});
}
});import { defineServer } from '@ogygia/core/plugin';
export default defineServer({
done(ctx) {
return fetch('https://logs.example.com/hit', {
method: 'POST',
body: ctx.path
}).then(() => {});
}
});Shared hooks
Shared hooks are how plugins call each other without importing each other. A plugin implements one as a method of its server half, and any server code calls it through app:
app.notify.<hook>(…)runs the hook on every plugin that has it, in plugin order, and resolves once all have run. One that throws is reported withplugin_hook_failedand doesn’t stop the others, and after they’ve all run the call rejects with that error (anAggregateErrorwhen several failed), so “done” and “done, but one couldn’t” are different answers.app.ask.<hook>(…)returns the first answer that isn’tundefined, in plugin order. One that throws is reported and skipped. When nobody answered and one threw, the call throws that error rather than answerundefined.
Nobody implementing a hook is normal: notify resolves and ask answers undefined.
Core owns these names:
| Hook | Kind | Contract |
|---|---|---|
invalidate(tags) | notify | Drop every stored page that carries any of tags. Never announce it again. |
invalidated(tags) | notify | Stored pages were dropped: tags names which (p:<path>, s:<source>:<fp>), or 'all'. |
lastBuild(version) | ask | Record version as the build the shared store last saw, and answer the one before, or undefined. |
measures(event) | ask | Is this visitor one the plugin measures for, proved by its own credentials? Region answers then carry a server-timing header. undefined when the plugin can’t tell. |
codeOrigins() | sync | Origins that island code on this app’s pages may load from besides its own. Every plugin’s answer counts; read by core, not through ask. |
A plugin’s own hooks carry its name, so they never clash, and are typed by declaration merging:
The build reads which of core’s hooks each server half implements from the keys of its defineServer({ … }), so a hook core calls on every request, like measures, costs nothing where no plugin has it. A server half the build can’t read counts as implementing all of them.
import { defineServer } from '@ogygia/core/plugin';
declare module '@ogygia/core/plugin' {
interface ServerHooks {
stampReset(path: string): void;
}
}
export default defineServer({
stampReset(path) {
console.info(`reset ${path}`);
},
async request(ctx) {
if (ctx.path === '/__stamp/reset') {
await ctx.app.notify.stampReset('/');
return new Response(null, { status: 204 });
}
}
});