Hooks

On this page

Hooks let plugins run code in response to events. All hooks receive an event object and the plugin context, and they’re declared at plugin definition time — there’s no dynamic registration at runtime.

This page covers sandboxed plugins. Native plugins use the same hook names and event types, but they use the in-process hook pipeline and can additionally register page:fragments. Sandboxed save rejection and isolated-runner failure behavior are described below.

Hook signature

Every hook handler takes two arguments:

async (event, ctx) => ReturnType;
  • event — data about what just happened (content being saved, media uploaded, lifecycle transition, etc.)
  • ctx — the PluginContext with storage, KV, logging, and capability-gated APIs

Assigning the definition to a SandboxedPlugin-typed constant infers event from the hook name (the full canonical event type) and ctx as PluginContext, so handlers need no parameter annotations. Export that constant as default. To reference an event type by name in a helper, import it from emdash/plugin.

Hook configuration

A hook can be declared as a bare handler or wrapped in a config object. Prefer the bare form unless the plugin also supports deliberate in-process execution and needs the metadata described below.

Simple

hooks: {
	"content:afterSave": async (event, ctx) => {
		ctx.log.info("Content saved");
	},
},

Full config

hooks: {
	"content:afterSave": {
		priority: 100,
		timeout: 5000,
		handler: async (event, ctx) => {
			ctx.log.info("Content saved");
		},
	},
},

Configuration options

OptionTypeDefaultDescription
prioritynumber100Execution order. Lower numbers run first.
timeoutnumber5000Maximum execution time in milliseconds.
exclusivebooleanfalseOnly one plugin can be the active provider. Used for email:deliver and comment:moderate.
handlerfunctionThe hook handler function. Required.

Required capabilities

Several hooks expose protected data or can change an operation. EmDash registers them only when the manifest declares the matching capability:

HooksCapabilityReason
content:beforeSavecontent:writeThe hook can replace submitted content.
Other content:* hookscontent:readTheir events expose content or identify an entry.
media:beforeUploadmedia:writeThe hook can replace upload metadata or stop the upload.
media:afterUploadmedia:readIts event exposes the stored media item.
email:beforeSend, email:afterSendhooks.email-events:registerThe hooks inspect email lifecycle events.
email:deliverhooks.email-transport:registerThe hook becomes an email transport provider.
All comment:* hooksusers:readComment events can contain author contact information and request metadata.
page:fragmentshooks.page-fragments:registerThe hook injects first-party page content and is native-only.

Lifecycle hooks, cron, and page:metadata have no registration capability. Declare the listed capability even when a hook only reads its event and does not call the matching ctx API. The declaration gives the operator an accurate consent prompt, gates the ctx API, and is required when the plugin runs in process. Capabilities and security explains the runtime effect.

Lifecycle hooks

Run during plugin installation, activation, deactivation, and removal.

plugin:install

Runs once when the plugin is first added to a site.

This example assumes the manifest declares an items storage collection:

"plugin:install": async (_event, ctx) => {
	ctx.log.info("Installing plugin...");
	await ctx.kv.set("settings:enabled", true);
	await ctx.storage.items.put("default", { name: "Default Item" });
},

Event: {}Returns: Promise<void>

plugin:activate

Runs when the plugin is enabled (after install or when re-enabled).

"plugin:activate": async (_event, ctx) => {
	ctx.log.info("Plugin activated");
},

Event: {}Returns: Promise<void>

plugin:deactivate

Runs when the plugin is disabled (but not removed).

"plugin:deactivate": async (_event, ctx) => {
	ctx.log.info("Plugin deactivated");
},

Event: {}Returns: Promise<void>

plugin:uninstall

Runs when the plugin is removed from a site.

"plugin:uninstall": async (event, ctx) => {
	ctx.log.info("Uninstalling plugin...");
	if (event.deleteData) {
		while (true) {
			const result = await ctx.storage.items.query({ limit: 100 });
			if (result.items.length === 0) break;
			await ctx.storage.items.deleteMany(result.items.map((item) => item.id));
		}
	}
},

Event: { deleteData: boolean }Returns: Promise<void>

Content hooks

Run during create, update, and delete operations on site content.

content:beforeSave

Runs before content is saved. Return modified content, a sandbox hook error result, or void to leave it unchanged.

To reject a save from the sandbox, return a versioned hook result with a SAVE_REJECTED error. Set reason to plain text between 1 and 500 characters. EmDash identifies the plugin and shows the reason to the editor. Empty, overlong, malformed, and unknown error results fail the save with a generic hook error.

"content:beforeSave": async (event, ctx) => {
	const { content } = event;
	if (typeof content.title !== "string" || content.title.trim() === "") {
		return {
			__emdashSandboxHookResult: true,
			version: 1,
			error: {
				code: "SAVE_REJECTED",
				reason: "Add a title before saving.",
			},
		};
	}

	if (typeof content.slug === "string") {
		content.slug = content.slug.toLowerCase().replace(/\s+/g, "-");
	}

	return content;
},

Do not put HTML in reason. The admin renders the value as text.

From the host process, throw ContentSaveRejectedError (exported from emdash) instead. The API returns SAVE_REJECTED with your message. Any other exception from either execution mode fails the save with a generic CONTENT_HOOK_ERROR response.

Event: { content, collection, isNew, id, actor }Returns: modified content, a sandbox hook error result, or void. On an update, id is the ID of the existing item and content holds only the submitted field values; load the stored item with ctx.content.get(event.collection, event.id). Authenticated REST, visual editing, and MCP saves include actor.id and the numeric actor.role. Internal writes without an authenticated user omit actor.

content:afterSave

Runs after content is successfully saved. Use for side effects like notifications, logging, or external syncs.

"content:afterSave": async (event, ctx) => {
	const contentId = String(event.content.id);
	ctx.log.info(`${event.isNew ? "Created" : "Updated"} ${event.collection}/${contentId}`, {
		actorId: event.actor?.id,
	});

	if (ctx.http) {
		await ctx.http.fetch("https://api.example.com/webhook", {
			method: "POST",
			body: JSON.stringify({ event: "content:save", id: contentId }),
		});
	}
},

Event: { content, collection, isNew, actor }Returns: Promise<void>. Authenticated saves include the same optional actor snapshot as content:beforeSave.

content:beforeDelete

Runs before content is deleted. Return false to cancel; true or void allows it.

"content:beforeDelete": async (event, ctx) => {
	if (event.collection === "pages" && event.id === "home") {
		ctx.log.warn("Cannot delete home page");
		return false;
	}
	return true;
},

Event: { id, collection, permanent: false }Returns: boolean | void

This hook runs before an entry is moved to trash. Removing an entry permanently from trash does not run content:beforeDelete again.

content:afterDelete

Runs after content is successfully deleted.

"content:afterDelete": async (event, ctx) => {
	await ctx.storage.cache.delete(`${event.collection}:${event.id}`);
},

Event: { id, collection, permanent }Returns: Promise<void>. permanent is false when the entry was moved to trash and true when the entry was removed permanently.

content:afterPublish

Runs after content is promoted from draft to live. Requires content:read capability.

Event: { content, collection }Returns: Promise<void>

content:afterUnpublish

Runs after content is reverted from live to draft. Requires content:read capability.

Event: { content, collection }Returns: Promise<void>

content:afterRestore

Runs after trashed content is restored. Requires content:read capability.

Event: { content, collection }Returns: Promise<void>

content:afterSchedule

Runs after content is scheduled for future publishing. Requires content:read capability.

Event: { content, collection }Returns: Promise<void>

content:afterUnschedule

Runs after scheduled content is unscheduled. Requires content:read capability.

Event: { content, collection }Returns: Promise<void>

Media hooks

media:beforeUpload

Runs before a file is uploaded. Return modified file metadata or throw to cancel.

"media:beforeUpload": async (event, ctx) => {
	if (!event.file.type.startsWith("image/")) {
		throw new Error("Only images are allowed");
	}
	if (event.file.size > 10 * 1024 * 1024) {
		throw new Error("File too large");
	}
	return { ...event.file, name: `${Date.now()}-${event.file.name}` };
},

Event: { file: { name, type, size } }Returns: modified file or void

media:afterUpload

Runs after a file is successfully uploaded.

Event: { media: { id, filename, mimeType, size, url, createdAt } }Returns: Promise<void>

Public-page hooks

These let plugins contribute to rendered public pages. Templates opt in by including the <EmDashHead>, <EmDashBodyStart>, and <EmDashBodyEnd> components from emdash/ui.

page:metadata

Contributes typed metadata to <head> — meta tags, OpenGraph properties, allowlisted <link> rels, and JSON-LD. Available to both sandboxed and native plugins. Core validates, deduplicates, and renders the contributions; plugins return structured data, never raw HTML.

"page:metadata": async (event, ctx) => {
	if (event.page.kind !== "content") return null;

	return {
		kind: "jsonld",
		id: `schema:${event.page.content?.collection}:${event.page.content?.id}`,
		graph: {
			"@context": "https://schema.org",
			"@type": "BlogPosting",
			headline: event.page.pageTitle ?? event.page.title,
			description: event.page.description,
		},
	};
},

Event:

{
	page: {
		url: string;
		path: string;
		locale: string | null;
		kind: "content" | "custom";
		pageType: string;
		title: string | null;
		pageTitle?: string | null;
		description: string | null;
		canonical: string | null;
		image: string | null;
		content?: { collection: string; id: string; slug: string | null };
		seo?: {
			ogTitle?: string | null;
			ogDescription?: string | null;
			ogImage?: string | null;
			robots?: string | null;
		};
		articleMeta?: {
			publishedTime?: string | null;
			modifiedTime?: string | null;
			author?: string | null;
		};
		siteName?: string;
		breadcrumbs?: Array<{ name: string; url: string }>;
		siteUrl?: string;
	}
}

Returns: PageMetadataContribution | PageMetadataContribution[] | null

Contribution kinds:

KindRendersDedupe key
meta<meta name="..." content="...">key or name
property<meta property="..." content="...">key or property
link<link rel="<allowed value>" href="...">canonical: singleton; alternate: key or hreflang
jsonld<script type="application/ld+json">id (if present)

First contribution wins for any dedupe key. <EmDashHead> composes contributions in the order plugins → site settings → template-provided base metadata, so plugin contributions override everything below them. On content pages, the entry’s SEO panel values are folded into the page context before the base metadata is generated — they replace the template-provided fields (and are what your hook sees on the page context), while plugin contributions still win via first-wins dedup. Link rel is restricted to a security-locked allowlist (canonical, alternate, author, license, nlweb, site.standard.document); href must be HTTP or HTTPS.

page:fragments

Contributes raw HTML, scripts, or stylesheets to page insertion points. Native plugins only.

Sandboxed plugins can’t use this hook because its output runs as first-party code in the visitor’s browser, outside any sandbox boundary. For sandbox-safe page contributions, use page:metadata. See Native plugins: page fragments if you need this surface.

Hook execution order

When a sandboxed-format plugin runs in process, hooks use the shared hook pipeline:

  1. Hooks with lower priority values run first.
  2. For equal priorities, hooks run in plugin registration order.
  3. Hooks with dependencies wait for those plugins to complete.
// Plugin A
"content:afterSave": { priority: 50, handler: async () => {} }

// Plugin B
"content:afterSave": { priority: 100, handler: async () => {} }

// Plugin C
"content:afterSave": {
	priority: 200,
	dependencies: ["plugin-a"],   // waits for A even if its priority would normally be later
	handler: async () => {},
}

An isolated sandbox runner invokes active sandboxed plugins in load order. Keep hooks independent: do not require one sandboxed plugin to run before another.

Error handling

Sandboxed hook failures depend on when the hook runs:

  • A thrown content:beforeSave error fails the save with CONTENT_HOOK_ERROR. Return the documented SAVE_REJECTED envelope when the editor should see a specific validation reason.
  • Returning false from content:beforeDelete stops the move to trash. If that hook throws, EmDash logs the error and continues the deletion.
  • Content after-hooks run after the operation succeeds. Their errors are logged and cannot roll the operation back.
  • Lifecycle, media, email, and comment hooks follow the contract of their originating operation. Use the Hook reference to check a specific return value before relying on failure behavior.

An in-process plugin can use errorPolicy: "abort" or "continue" in the full config form. That setting is not a portable recovery control for an isolated sandboxed plugin.

Timeouts

The in-process hook pipeline defaults to 5,000 ms and accepts a longer timeout in the full config form:

"content:afterSave": {
	timeout: 30000,
	handler: async (event, ctx) => {
		// Long-running operation
	},
},

Hook reference

HookTriggerReturnExclusive
plugin:installFirst plugin installationvoidNo
plugin:activatePlugin enabledvoidNo
plugin:deactivatePlugin disabledvoidNo
plugin:uninstallPlugin removedvoidNo
content:beforeSaveBefore content saveModified content, rejection envelope, or voidNo
content:afterSaveAfter content savevoidNo
content:beforeDeleteBefore content moves to trashfalse to cancel, else allowNo
content:afterDeleteAfter trash or permanent deletevoidNo
content:afterPublishAfter content publishvoidNo
content:afterUnpublishAfter content unpublishvoidNo
content:afterRestoreAfter content restorevoidNo
content:afterScheduleAfter content schedulevoidNo
content:afterUnscheduleAfter content unschedulevoidNo
media:beforeUploadBefore file uploadModified file info or voidNo
media:afterUploadAfter file uploadvoidNo
cronScheduled task firesvoidNo
email:beforeSendBefore email deliveryModified message, false, or voidNo
email:deliverDeliver email via transportvoidYes
email:afterSendAfter email deliveryvoidNo
comment:beforeCreateBefore comment storedModified event, false, or voidNo
comment:moderateDecide comment status{ status, reason? }Yes
comment:afterCreateAfter comment storedvoidNo
comment:afterModerateAdmin changes comment statusvoidNo
page:metadataPage renderContributions or nullNo
page:fragmentsPage render (native only)Contributions or nullNo

See the Hook Reference for complete event types and handler signatures.