@notionhq/custom-blocks-host
v0.10.0
Published
Reusable host runtime for Notion custom blocks.
Maintainers
Keywords
Readme
@notionhq/custom-blocks-host
The host manages the bridge between your application and a custom block iframe. Your application
owns the iframe, permissions, data access, persistence, analytics, and UI. Block authors use
@notionhq/custom-blocks.
Create the host before navigating the iframe. Pass the full block URL as sandboxUrl, and call
stop() when removing the iframe. A host instance belongs to the required viewerId. Supply one
asynchronous getCurrentUser profile reader; its returned ID must match that viewer. Create a fresh
host and iframe when the viewer changes.
For configuration and lifecycle details, see Initialization and lifecycle.
For platform handlers, signal-based live queries, and explicit partial implementations, see the
Host contract. The host accepts CustomBlockHostOptions.
Use BridgeParent from @notionhq/custom-blocks-host/protocol to construct parent references with
plain string IDs. The host validates the parent before sending it to the block.
Implement CustomBlockHostHandlers to connect the host to your application. Result-returning
handlers return promises. CustomBlockHostHandler<Args, Payload> supplies the shared signature and
request context. Handlers return shared bridge data using CustomBlockHostHandlerResult. Use
makeBridgePage to construct a complete BridgePage from your records. See
Return bridge data.
Create a host
Install @notionhq/custom-blocks-host in your embedding application. Run this TypeScript through
your browser bundler after the document body exists.
This example embeds a block with no data sources and supplies fixed demo context. Replace
https://blocks.example.com/hello with your block's URL. Serve the block from a different origin
than the embedding application.
import { createCustomBlockHost, hostHandlerNotImplemented } from "@notionhq/custom-blocks-host"
function mountCustomBlock(container: HTMLElement, blockUrl: URL): () => void {
if (
!["http:", "https:"].includes(blockUrl.protocol) ||
blockUrl.origin === window.location.origin
) {
throw new Error("The block needs an HTTP or HTTPS URL on a separate origin")
}
const wrapper = document.createElement("section")
const status = document.createElement("p")
status.setAttribute("role", "status")
status.textContent = "Loading block…"
const iframe = document.createElement("iframe")
iframe.title = "Hello custom block"
iframe.setAttribute("sandbox", "allow-scripts allow-same-origin")
iframe.allow = "clipboard-write"
iframe.style.width = "100%"
iframe.style.height = "300px"
iframe.style.visibility = "hidden"
wrapper.append(status, iframe)
container.append(wrapper)
function setHeight(height: number) {
iframe.style.height = `${Math.min(1200, Math.max(120, height))}px`
}
const host = createCustomBlockHost({
iframe,
blockId: "11111111-1111-4111-8111-111111111111",
viewerId: "33333333-3333-4333-8333-333333333333",
getCurrentUser: async () => ({
object: "user",
id: "33333333-3333-4333-8333-333333333333",
type: "person",
name: "Demo viewer",
avatar_url: null,
person: { email: "[email protected]" },
}),
theme: "light",
contrastMode: "standard",
containingPage: {
type: "page",
id: "22222222-2222-4222-8222-222222222222",
parent: { type: "workspace", workspace: true },
},
parent: {
type: "page_id",
page_id: "22222222-2222-4222-8222-222222222222",
},
sandboxUrl: blockUrl.href,
manifestSource: "host",
getPersistedManifest: async () => ({
status: "success",
manifest: { version: 1, dataSources: {} },
}),
bindings: { pages: {}, dataSources: {} },
handlers: {
getDataSource: async () => ({ status: "success", state: { status: "unavailable" } }),
subscribeToQuery: ({ onError }) => onError(hostHandlerNotImplemented("subscribeToQuery")),
getPage: async () => ({ status: "error", error: hostHandlerNotImplemented("getPage") }),
createPage: async () => ({ status: "error", error: hostHandlerNotImplemented("createPage") }),
updatePage: async () => ({ status: "error", error: hostHandlerNotImplemented("updatePage") }),
getUser: async () => ({ status: "error", error: hostHandlerNotImplemented("getUser") }),
listUsers: async () => ({ status: "error", error: hostHandlerNotImplemented("listUsers") }),
openPage: async () => ({ status: "error", error: hostHandlerNotImplemented("openPage") }),
openExternalUrl: async () => ({
status: "error",
error: hostHandlerNotImplemented("openExternalUrl"),
}),
resize: message => setHeight(message.height),
},
onStatusChange: state => {
if (state.status === "initialized") {
setHeight(state.initialHeight ?? 300)
status.hidden = true
iframe.style.visibility = "visible"
} else if (state.status === "failed") {
iframe.style.visibility = "hidden"
status.hidden = false
status.textContent = `Block failed: ${state.error.code}`
}
},
})
// The host must listen before the block starts its handshake.
iframe.src = blockUrl.href
return () => {
host.stop()
wrapper.remove()
}
}
const dispose = mountCustomBlock(document.body, new URL("https://blocks.example.com/hello"))
window.addEventListener("pagehide", dispose, { once: true })You should see “Loading block…” until the block completes initialization, then the block iframe. A connection failure displays its error code. The example limits the iframe height to 120–1,200 CSS pixels.
Call dispose() when your application removes the embed. To retry a failed connection or change the
block URL, dispose of the current embed and call mountCustomBlock() again.
Initial theme, contrastMode, containingPage, and parent may be null while loading. Call
the corresponding setters as values resolve. The shared host waits for all four before sending
init. The wait counts toward initialStateTimeoutMs after connect. Setters take resolved values
only. For containing-page context, { type: "unavailable" } means denied access, distinct from
loading.
For a production integration, replace the demo context and manifest with your application's values. Supply data-source bindings and handlers for the APIs your block uses. Your application must enforce permissions and record access.
To connect workspace data, see Connect a data source.
Guides and reference
- Initialization and lifecycle: manifests, context, timeouts, live state, and cleanup.
- Handlers and data: application handlers, data-source integration, queries, and navigation.
- Host compatibility: supported versions and response conversions.
The runtime handles the wire handshake and message validation. The shared protocol references cover payload semantics, version rules, and contract history:
Protocol schemas and types
The /protocol entrypoint exposes the protocol definitions bundled with this host release. It
provides message schemas and types, data shapes, IDs, error definitions, and protocol-version
constants.
Import these definitions through the host package to use the protocol version shipped with that host:
import {
sandboxToHostMessageSchema,
type SandboxToHostMessage,
} from "@notionhq/custom-blocks-host/protocol"LATEST_BRIDGE_PROTOCOL_VERSION identifies the latest bridge protocol version defined by the
bundled protocol.
Host APIs, configuration, handler results, and domain argument types are available from
@notionhq/custom-blocks-host.
These schemas validate wire payloads. Your application still enforces permissions.
Standalone browser module
dist/browser.js is one ES module with all dependencies. Use it when the browser must not fetch
additional modules, such as under an exact-URL Content Security Policy.
Native page icons
CustomBlockHostPageIcon accepts canonical native icon names from hosts. Hosts validate names and
colors before writing. The runtime validates response payloads.
Hosts must check URL-backed icon and cover writes against the block's network permissions before mutating records. Notion permits the submitted HTTPS destination only when its origin is allowlisted; that origin is trusted to redirect.
