Build a GitBook Integration
A skill for building integrations on GitBook's developer platform: apps that run inside GitBook itself. An integration can render custom blocks in the editor, show configuration UI, listen to events (content updated, Git sync completed, space viewed), authenticate against external services with OAuth, and talk to anything over HTTP.
This skill covers the integration lifecycle — scaffold, code, develop, publish. For creating or restructuring the docs site an integration might be installed into, defer to configure-site; for authoring page content, defer to write-docs.
What an integration is (mental model)
An integration is a small TypeScript app executed by GitBook's runtime — not a script injected into pages, and not code running on the user's server. Three consequences shape everything else:
- Rendering happens on GitBook's backend. Your component's
render function runs server-side on every interaction and returns ContentKit markup (a JSX-like UI description). There is no client-side React tree you control, no DOM access, and UI updates flow through the action → new state → re-render loop.
- You cannot inject JavaScript into a site. The
site:script:inject and site:script:cookies scopes you'll see in GitBook-owned integrations are internal-only. If the user's plan amounts to "add a script tag to their docs", stop and say so early — the supported paths are custom blocks, webframes, and events.
- Local development is a proxy, not a server you visit.
gitbook dev routes the installed integration's traffic to your machine. You never open the dev server's port in a browser; you interact with the integration inside app.gitbook.com.
The project
gitbook new scaffolds this shape:
my-integration/
├── gitbook-manifest.yaml # identity, scopes, blocks, configuration schema
├── .gitbook-dev.yaml # local dev config (generated by `gitbook dev`)
├── package.json
└── src/
└── index.tsx # entry file — default-exports createIntegration()
The entry file (whatever script: in the manifest points to) default-exports createIntegration({ fetch, components, events }):
import { createIntegration, createComponent } from '@gitbook/runtime';
const helloBlock = createComponent({
componentId: 'hello-world', // must match a block id in the manifest
initialState: { message: 'Say hello!' },
action: async (element, action, context) => {
switch (action.action) {
case 'say':
return { state: { message: 'Hello world' } };
default:
return {};
}
},
render: async (element, context) => (
<block>
<button label={element.state.message} action: 'say' }} />
</block>
),
});
export default createIntegration({
components: [helloBlock],
events: {
space_content_updated: async (event, context) => {
// react to content changes
},
},
});
A custom block only appears in the editor's insert palette (⌘ + /) if it is declared in both places: createComponent in the code and a blocks: entry in the manifest whose id matches the componentId. Forgetting one half is the most common "my block doesn't show up" cause.
The manifest, briefly
gitbook-manifest.yaml is the integration's identity and permission grant. Required: name (globally unique across all of GitBook — pick something namespaced like acme-changelog, not test), title, description, organization (org id or subdomain), visibility, scopes, and script. Request only the scopes the code actually uses — installers see them.
The manifest also declares blocks, installer-facing configurations (account-level and site-level property schemas rendered as a settings form), and secrets (e.g. CLIENT_ID: ${{ env.CLIENT_ID }}, loaded at publish time — use dotenv-cli so gitbook publish sees your .env).
Full field-by-field schema, scope list, and configuration property types: references/manifest.md. Read it whenever you're editing the manifest beyond the basics.
The development loop
The loop has a non-obvious order — publish comes before local development:
- Prerequisites. Node 18+, a personal access token from https://app.gitbook.com/account/developer, and the CLI:
npm install @gitbook/cli -g, then gitbook auth (or gitbook auth --token=<token>). If a token needs to be pasted into the conversation, export it to the environment and never echo it back or commit it.
- Scaffold.
gitbook new <dir> — prompts for name, title, organization, and scopes.
- Publish once.
gitbook publish in the project root. This registers the integration (private by default) and prints an install link.
- Install it into at least one space or site via that link. Local dev doesn't work until it's installed somewhere.
- Develop.
gitbook dev starts the proxy: all traffic for the installed integration is served from your local code instead of the published version. Interact with it in the GitBook editor, not at the server URL. UI changes need a browser refresh; disable browser caching for a smoother loop. Logs surface in the browser console or your terminal depending on where the code runs — check both before concluding logging is broken.
- Re-publish with
gitbook publish whenever you want the hosted version updated. gitbook unpublish <name> removes it.
CLI command reference (including gitbook whoami and gitbook openapi publish): references/manifest.md.
Runtime: fetch, events, environment, OAuth
Details and full tables live in references/runtime.md — read it when writing event handlers, OAuth flows, or anything touching context.environment. The essentials:
fetch handles incoming HTTP requests to the integration's public endpoint using standard Fetch API Request/Response objects. Outgoing HTTP is plain fetch too.
events maps event names (installation_setup, space_installation_setup, space_view, ui_render, space_content_updated, space_visibility_updated, space_gitsync_started, space_gitsync_completed) to handlers. Some events require matching scopes.
context.environment exposes apiEndpoint, apiTokens, installation info (space, status, per-installation configuration values entered by the installer), secrets, and public URLs (environment.integration.urls.publicEndpoint).
- OAuth against an external provider is a fixed pattern: a
button-type configuration property whose callback_url routes to a createOAuthHandler({...}) in your fetch handler, with client id/secret coming from secrets. Don't hand-roll the redirect/token exchange.
- Calling the GitBook API from inside the integration: use
context.api (an authenticated @gitbook/api client) rather than constructing your own client from raw tokens.
ContentKit: building the UI
ContentKit is the component vocabulary render can return: layout (block, vstack, hstack, divider), display (box, card, text, image, markdown), and interactive elements (button, textinput, select, switch, checkbox, radio, codeblock, webframe, modal). Interactivity model in one line: inputs bind their value to a state key; buttons dispatch actions; your action reducer returns new state; GitBook re-renders.
Read references/contentkit.md before writing any component beyond a trivial button — it has the full prop tables plus the patterns that are hard to guess: dynamic state binding for live previews, webframe postMessage communication, modals with returnValue, persisting props with @editor.node.updateProps, link unfurling via @link.unfurl + urlUnfurl manifest patterns, and markdown code-block serialization of blocks.
Publishing and sharing
Visibility in the manifest controls reach:
private (default) — installable only by members of the owning org. Right for internal tools; stay here during development.
unlisted — installable by any org, but only via the shared install link. Right for sharing with specific customers or beta testers.
public — installable by anyone; required before submitting to the integration marketplace (which is a separate review process — see GitBook's "submit your app for review" docs).
Re-run gitbook publish after changing visibility. Before suggesting public, sanity-check the manifest is presentable: icon, summary (Markdown, ≤2048 chars), previewImages (1600×800), categories, externalLinks.
Working style
- Scaffold with the CLI rather than by hand when starting fresh —
gitbook new wires up the manifest, TypeScript config, and @gitbook/runtime versions correctly.
- Trace a block's id chain (manifest
blocks[].id ↔ componentId) whenever a component misbehaves.
- Keep secrets out of the manifest file itself — always the
${{ env.X }} indirection, never literal values.
- When the user's goal is content or site automation from outside GitBook (scripts hitting the REST API, CI pipelines), an integration may be the wrong tool — the plain API with a personal token is simpler. Integrations earn their keep when code must run inside GitBook: blocks, config UI, event reactions, OAuth on behalf of installers.
References
references/manifest.md — every gitbook-manifest.yaml field, all scopes, configuration property types, secrets, CLI command reference, installation/configuration flow.
references/runtime.md — createIntegration / createComponent / createOAuthHandler signatures, event catalog, context.environment shape, HTTP in and out.
references/contentkit.md — full component reference with props, built-in actions, and interactivity recipes (dynamic binding, webframes, modals, unfurling, markdown serialization).
1---2name: build-integration3description: Build, develop, and publish GitBook integrations — apps that run inside GitBook to add custom blocks, react to events, connect external services via OAuth, and extend the editor. Use this skill whenever a task involves the GitBook integrations platform: scaffolding an integration with the GitBook CLI (`gitbook new`), writing or editing an integration's code (`createIntegration`, `createComponent`, ContentKit TSX), configuring `gitbook-manifest.yaml` (scopes, blocks, configurations, secrets), building custom editor blocks or link unfurlers, handling GitBook events like `space_content_updated`, setting up an integration's OAuth flow, running `gitbook dev`, or publishing an integration (private/unlisted/public, marketplace submission). Trigger this even if the user just says they want to 'build an app for GitBook', 'add a custom block', or 'connect <some tool> to GitBook' without saying the word 'integration'.4---56# Build a GitBook Integration78A skill for building integrations on GitBook's developer platform: apps that run inside GitBook itself. An integration can render custom blocks in the editor, show configuration UI, listen to events (content updated, Git sync completed, space viewed), authenticate against external services with OAuth, and talk to anything over HTTP.910This skill covers the integration lifecycle — scaffold, code, develop, publish. For creating or restructuring the docs *site* an integration might be installed into, defer to `configure-site`; for authoring page content, defer to `write-docs`.1112## What an integration is (mental model)1314An integration is a small TypeScript app executed by GitBook's runtime — not a script injected into pages, and not code running on the user's server. Three consequences shape everything else:15161. **Rendering happens on GitBook's backend.** Your component's `render` function runs server-side on every interaction and returns ContentKit markup (a JSX-like UI description). There is no client-side React tree you control, no DOM access, and UI updates flow through the action → new state → re-render loop.172. **You cannot inject JavaScript into a site.** The `site:script:inject` and `site:script:cookies` scopes you'll see in GitBook-owned integrations are internal-only. If the user's plan amounts to "add a script tag to their docs", stop and say so early — the supported paths are custom blocks, webframes, and events.183. **Local development is a proxy, not a server you visit.** `gitbook dev` routes the *installed* integration's traffic to your machine. You never open the dev server's port in a browser; you interact with the integration inside app.gitbook.com.1920## The project2122`gitbook new` scaffolds this shape:2324```25my-integration/26├── gitbook-manifest.yaml # identity, scopes, blocks, configuration schema27├── .gitbook-dev.yaml # local dev config (generated by `gitbook dev`)28├── package.json29└── src/30 └── index.tsx # entry file — default-exports createIntegration()31```3233The entry file (whatever `script:` in the manifest points to) default-exports `createIntegration({ fetch, components, events })`:3435```tsx36import { createIntegration, createComponent } from '@gitbook/runtime';3738const helloBlock = createComponent({39 componentId: 'hello-world', // must match a block id in the manifest40 initialState: { message: 'Say hello!' },41 action: async (element, action, context) => {42 switch (action.action) {43 case 'say':44 return { state: { message: 'Hello world' } };45 default:46 return {};47 }48 },49 render: async (element, context) => (50 <block>51 <button label={element.state.message} onPress={{ action: 'say' }} />52 </block>53 ),54});5556export default createIntegration({57 components: [helloBlock],58 events: {59 space_content_updated: async (event, context) => {60 // react to content changes61 },62 },63});64```6566A custom block only appears in the editor's insert palette (⌘ + /) if it is declared in **both** places: `createComponent` in the code *and* a `blocks:` entry in the manifest whose `id` matches the `componentId`. Forgetting one half is the most common "my block doesn't show up" cause.6768## The manifest, briefly6970`gitbook-manifest.yaml` is the integration's identity and permission grant. Required: `name` (globally unique across all of GitBook — pick something namespaced like `acme-changelog`, not `test`), `title`, `description`, `organization` (org id or subdomain), `visibility`, `scopes`, and `script`. Request only the scopes the code actually uses — installers see them.7172The manifest also declares `blocks`, installer-facing `configurations` (account-level and site-level property schemas rendered as a settings form), and `secrets` (e.g. `CLIENT_ID: ${{ env.CLIENT_ID }}`, loaded at publish time — use `dotenv-cli` so `gitbook publish` sees your `.env`).7374Full field-by-field schema, scope list, and configuration property types: `references/manifest.md`. Read it whenever you're editing the manifest beyond the basics.7576## The development loop7778The loop has a non-obvious order — **publish comes before local development**:79801. **Prerequisites.** Node 18+, a personal access token from https://app.gitbook.com/account/developer, and the CLI: `npm install @gitbook/cli -g`, then `gitbook auth` (or `gitbook auth --token=<token>`). If a token needs to be pasted into the conversation, export it to the environment and never echo it back or commit it.812. **Scaffold.** `gitbook new <dir>` — prompts for name, title, organization, and scopes.823. **Publish once.** `gitbook publish` in the project root. This registers the integration (private by default) and prints an install link.834. **Install it** into at least one space or site via that link. Local dev doesn't work until it's installed somewhere.845. **Develop.** `gitbook dev` starts the proxy: all traffic for the installed integration is served from your local code instead of the published version. Interact with it in the GitBook editor, not at the server URL. UI changes need a browser refresh; disable browser caching for a smoother loop. Logs surface in the *browser* console or your terminal depending on where the code runs — check both before concluding logging is broken.856. **Re-publish** with `gitbook publish` whenever you want the hosted version updated. `gitbook unpublish <name>` removes it.8687CLI command reference (including `gitbook whoami` and `gitbook openapi publish`): `references/manifest.md`.8889## Runtime: fetch, events, environment, OAuth9091Details and full tables live in `references/runtime.md` — read it when writing event handlers, OAuth flows, or anything touching `context.environment`. The essentials:9293- **`fetch`** handles incoming HTTP requests to the integration's public endpoint using standard Fetch API `Request`/`Response` objects. Outgoing HTTP is plain `fetch` too.94- **`events`** maps event names (`installation_setup`, `space_installation_setup`, `space_view`, `ui_render`, `space_content_updated`, `space_visibility_updated`, `space_gitsync_started`, `space_gitsync_completed`) to handlers. Some events require matching scopes.95- **`context.environment`** exposes `apiEndpoint`, `apiTokens`, installation info (space, status, per-installation `configuration` values entered by the installer), `secrets`, and public URLs (`environment.integration.urls.publicEndpoint`).96- **OAuth** against an external provider is a fixed pattern: a `button`-type configuration property whose `callback_url` routes to a `createOAuthHandler({...})` in your fetch handler, with client id/secret coming from `secrets`. Don't hand-roll the redirect/token exchange.97- **Calling the GitBook API from inside the integration**: use `context.api` (an authenticated `@gitbook/api` client) rather than constructing your own client from raw tokens.9899## ContentKit: building the UI100101ContentKit is the component vocabulary `render` can return: layout (`block`, `vstack`, `hstack`, `divider`), display (`box`, `card`, `text`, `image`, `markdown`), and interactive elements (`button`, `textinput`, `select`, `switch`, `checkbox`, `radio`, `codeblock`, `webframe`, `modal`). Interactivity model in one line: inputs bind their value to a `state` key; buttons dispatch actions; your `action` reducer returns new state; GitBook re-renders.102103Read `references/contentkit.md` before writing any component beyond a trivial button — it has the full prop tables plus the patterns that are hard to guess: dynamic state binding for live previews, webframe `postMessage` communication, modals with `returnValue`, persisting props with `@editor.node.updateProps`, link unfurling via `@link.unfurl` + `urlUnfurl` manifest patterns, and markdown code-block serialization of blocks.104105## Publishing and sharing106107Visibility in the manifest controls reach:108109- `private` (default) — installable only by members of the owning org. Right for internal tools; stay here during development.110- `unlisted` — installable by any org, but only via the shared install link. Right for sharing with specific customers or beta testers.111- `public` — installable by anyone; required before submitting to the integration marketplace (which is a separate review process — see GitBook's "submit your app for review" docs).112113Re-run `gitbook publish` after changing visibility. Before suggesting `public`, sanity-check the manifest is presentable: `icon`, `summary` (Markdown, ≤2048 chars), `previewImages` (1600×800), `categories`, `externalLinks`.114115## Working style116117- **Scaffold with the CLI rather than by hand** when starting fresh — `gitbook new` wires up the manifest, TypeScript config, and `@gitbook/runtime` versions correctly.118- **Trace a block's id chain** (manifest `blocks[].id` ↔ `componentId`) whenever a component misbehaves.119- **Keep secrets out of the manifest file itself** — always the `${{ env.X }}` indirection, never literal values.120- **When the user's goal is content or site automation from *outside* GitBook** (scripts hitting the REST API, CI pipelines), an integration may be the wrong tool — the plain API with a personal token is simpler. Integrations earn their keep when code must run *inside* GitBook: blocks, config UI, event reactions, OAuth on behalf of installers.121122## References123124- `references/manifest.md` — every `gitbook-manifest.yaml` field, all scopes, configuration property types, secrets, CLI command reference, installation/configuration flow.125- `references/runtime.md` — `createIntegration` / `createComponent` / `createOAuthHandler` signatures, event catalog, `context.environment` shape, HTTP in and out.126- `references/contentkit.md` — full component reference with props, built-in actions, and interactivity recipes (dynamic binding, webframes, modals, unfurling, markdown serialization).