Notion Integration Guide

Technology: notion · Category: docs · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/notion

Insight:

Notion is the docs / PM hub — automate status reports, spec-to-ticket conversion, and knowledge capture via the hosted MCP (https://mcp.notion.com/mcp, OAuth); the open-source local MCP server is no longer maintained. In code, use @notionhq/client 5.27.x pinned to Notion-Version: 2026-03-11 (the SDK still defaults to 2025-09-03): a database is a container of data sources, so query dataSources.query, trash with in_trash, and insert blocks with position. Rate limits are now plan-based (180 req/min per connection, 600 on Business/Enterprise) plus a shared per-workspace cap, and multi-member Free workspaces hit a 1,000-block limit through the API. Verify webhooks with verifyWebhookSignature(). Keep customer PII off synced pages (KDPA for Kenya-targeted projects).

███╗   ██╗ ██████╗ ████████╗██╗ ██████╗ ███╗   ██╗
████╗  ██║██╔═══██╗╚══██╔══╝██║██╔═══██╗████╗  ██║
██╔██╗ ██║██║   ██║   ██║   ██║██║   ██║██╔██╗ ██║
██║╚██╗██║██║   ██║   ██║   ██║██║   ██║██║╚██╗██║
██║ ╚████║╚██████╔╝   ██║   ██║╚██████╔╝██║ ╚████║
╚═╝  ╚═══╝ ╚═════╝    ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝

Notion Integration Guide

Focus: Automating documentation, project management, and knowledge-base workflows from Claude Code with the hosted Notion MCP and the Notion REST API (@notionhq/client).

Overview

Notion is an all-in-one workspace for docs, databases, wikis, and project management. It now has five developer surfaces, and picking the right one saves a lot of work:

Surface What it is Use it for
Notion MCP (hosted) Remote MCP server at https://mcp.notion.com/mcp, OAuth, Markdown-native tools Driving Notion conversationally from Claude Code, Cursor, Codex
REST API (@notionhq/client, notion-client) https://api.notion.com/v1, versioned by the Notion-Version header App code, CI scripts, Claude Code hooks
Webhooks Signed HTTP POSTs when pages, data sources, comments, views or file uploads change Reacting to workspace changes without polling
Notion Workers (beta) Notion-hosted TypeScript programs (@notionhq/workers, deployed with the ntn CLI) Scheduled syncs into Notion, tools for Custom Agents, inbound webhooks
Notion Agent APIs (public beta) Sessions/agents endpoints for Custom Agents Bringing a Custom Agent into Slack, an internal tool, or a mobile client

Terminology changed in 2026. Notion's docs now say connection where they used to say integration: an internal connection (one workspace, static ntn_… token, acts as its own bot), a public connection (OAuth, installs into many workspaces), and the new personal access token (PAT, acts as you). You manage all of them in the Developer portal (https://app.notion.com/developers; the old notion.so/profile/integrations links redirect there).

flowchart LR
  CC["Claude Code"] -->|"OAuth"| MCP["Hosted Notion MCP<br/>mcp.notion.com/mcp"]
  App["Your app / CI"] -->|"Bearer token + Notion-Version"| API["Notion REST API"]
  MCP --> WS["Notion workspace"]
  API --> WS
  WS -->|"signed webhook"| Hook["/api/webhooks/notion"]
  WS --> DB["Database<br/>holds data sources<br/>holds rows (pages)"]

Versions at a glance (verified 2026-10-20)

Thing Current Notes
Latest Notion-Version header 2026-03-11 Required on every REST request. Breaking changes vs 2025-09-03: archived→in_trash, append after→position, transcription block→meeting_notes
Data-source model since 2025-09-03 A database is a container of one or more data sources
@notionhq/client (npm) 5.27.1 (2026-10-16) Supports 2026-03-11 since 5.12.0, but its default is still 2025-09-03, so set notionVersion explicitly. Node ≥ 18
notion-client (PyPI) 3.1.0 (2026-05-12) Data-source model; default version 2025-09-03
@notionhq/notion-mcp-server (npm) 2.5.2 No longer actively maintained; use the hosted MCP
ntn (Notion CLI, npm) 0.23.20 Workers, ntn api … requests, file uploads. Node 22+ for the npm install
@notionhq/workers (npm) 0.9.3 Workers runtime library (beta)

Official Documentation

Resource URL
Notion Developers https://developers.notion.com
API reference https://developers.notion.com/reference
API versioning https://developers.notion.com/reference/versioning
Upgrade guide 2026-03-11 https://developers.notion.com/guides/get-started/upgrade-guide-2026-03-11
Upgrade guide 2025-09-03 (data sources) https://developers.notion.com/guides/get-started/upgrade-guide-2025-09-03
Request limits https://developers.notion.com/reference/request-limits
Webhooks https://developers.notion.com/reference/webhooks
Files and media https://developers.notion.com/guides/data-apis/working-with-files-and-media
Markdown content API https://developers.notion.com/guides/data-apis/working-with-markdown-content
Notion MCP https://developers.notion.com/guides/mcp/overview
Notion Agent APIs https://developers.notion.com/guides/notion-agent-apis/overview
Notion Workers https://developers.notion.com/workers/get-started/overview
Changelog https://developers.notion.com/page/changelog
JS SDK https://github.com/makenotion/notion-sdk-js

MCP Server Setup

claude mcp add --transport http notion https://mcp.notion.com/mcp

Then run /mcp inside Claude Code and finish the OAuth flow. Add --scope project to share it through .mcp.json (see examples/mcp-config.json), or --scope user for every project. Notion also ships a Claude Code plugin (makenotion/claude-code-notion-plugin) that bundles the server, Skills, and slash commands.

What you get, compared with the REST API:

Option B — Open-source local server (legacy)

@notionhq/notion-mcp-server (v2.x, API 2025-09-03, hyphenated tool names such as query-data-source) still installs. Notion says it is no longer actively maintained and may be sunset. Use it only when you need bearer-token auth for fully headless automation, with the token kept in the environment (never in a committed file):

claude mcp add notion-local -- npx -y @notionhq/notion-mcp-server   # reads NOTION_TOKEN from the env

For headless automation, a small script on @notionhq/client is usually the better choice.


Authentication — pick the right credential

Credential Acts as Page access Best for
Internal connection token (ntn_…) Its own bot user Only pages shared with the connection (••• → Connections, or the portal's Content access tab) Team-owned automations, CI, server jobs
Personal access token (PAT) You Everything you can access Local scripts, the ntn CLI, Workers, Agent APIs. Expires after 7/30/90/180 days or 1 year (default). Not for multi-user products
Public connection (OAuth 2.0) The authorizing user Pages picked in the OAuth page picker Products that many Notion workspaces install

How public-connection OAuth works:

  1. Send users to the authorization URL from the portal.
  2. Exchange the code at POST https://api.notion.com/v1/oauth/token with HTTP Basic auth (client_id:client_secret) and grant_type: "authorization_code". You get an access_token and a refresh_token.
  3. Refresh with grant_type: "refresh_token".

Since 2026-06-08, new public connections mint a fresh token pair on every authorization, so store the pair from every response. The SDK wraps this flow as notion.oauth.token(...), oauth.introspect, and oauth.revoke.

Installation scope is fixed when you create the connection: Any workspace (can be listed on the Marketplace) or Selected workspaces only.


REST API with @notionhq/client

npm install @notionhq/client@5.27.1
sequenceDiagram
  participant App as "Your Code"
  participant API as "Notion API"
  App->>API: "GET /v1/databases/:id"
  API-->>App: "data_sources[] (data_source_id)"
  App->>API: "POST /v1/data_sources/:id/query"
  API-->>App: "rows (pages), next_cursor"
  App->>API: "POST /v1/pages parent data_source_id + markdown"
  API-->>App: "new page id"
  App->>API: "PATCH /v1/blocks/:id/children position start"
  API-->>App: "appended blocks"
import { Client, isFullPage, collectAllDataSourceRows } from "@notionhq/client";

// Pin the latest API version: the SDK default is still 2025-09-03.
const notion = new Client({ auth: process.env.NOTION_TOKEN, notionVersion: "2026-03-11" });

// 1. Resolve the data source inside a database (single-source DBs use [0]).
const db = await notion.databases.retrieve({ database_id: process.env.NOTION_TASKS_DB_ID! });
if (!("data_sources" in db)) throw new Error("partial database response");
const dataSourceId = db.data_sources[0].id;

// 2. Query one page of rows (max page_size 100).
const res = await notion.dataSources.query({
  data_source_id: dataSourceId,
  filter: { property: "Status", status: { equals: "In progress" } },
  sorts: [{ property: "Due Date", direction: "ascending" }],
  page_size: 100,
});
const open = res.results.filter(isFullPage);

// 3. Every row, including past the 10,000-result cap of a single query.
const allRows = await collectAllDataSourceRows(notion, { data_source_id: dataSourceId });

// 4. Create a row with a Markdown body.
const page = await notion.pages.create({
  parent: { type: "data_source_id", data_source_id: dataSourceId },
  properties: {
    Name: { title: [{ text: { content: "Fix auth middleware" } }] },
    Status: { status: { name: "Not started" } },
    "Due Date": { date: { start: "2026-10-31" } },
  },
  markdown: "## Notes\n\nUse RS256 signing.",
});

// 5. Insert blocks at the top (2026-03-11: `position` replaces `after`).
await notion.blocks.children.append({
  block_id: page.id,
  position: { type: "start" },
  children: [
    { object: "block", type: "callout", callout: { rich_text: [{ type: "text", text: { content: "Auto-created" } }] } },
  ],
});

// 6. Trash it (2026-03-11: `in_trash` replaces `archived`).
await notion.pages.update({ page_id: page.id, in_trash: true });

console.log(open.length, allRows.length);

The full runnable version is examples/client.ts.

What else the API covers now

Area SDK method / endpoint Since
Markdown page content pages.retrieveMarkdown, pages.updateMarkdown (insert_content, update_content, replace_content, replace_content_range), pages.create({ markdown }) Feb–Mar 2026. The markdown_version: "v2" Notion-flavored Markdown preview (2026-09-30) is not yet typed in 5.27.1
Async large writes allow_async: true + asyncTasks.retrieve({ task_id }) 2026-06-29 / SDK 5.23.0
Views views.create/retrieve/update/delete/list, views.queries.* 2026-03-19 (needs 2025-09-03+)
Typed databases databases.create({ database_type: "tasks" | "projects" | "skills" }) 2026-09-02
Trash and archive search with filter.in_trash; dataSources.query({ is_archived: true }) 2026-07-15
Trim responses filter_properties on pages.create/pages.update and search 2026-08 / 2026-10
Meeting notes blocks.meetingNotes.create, query meeting notes 2026-05 / 5.24.0
Comments create, list, update, delete (with a markdown body) 2026-04
Custom Agents (beta) agents.*, sessions.* (stream, cancel, events) 2026-08-20

Python

pip install notion-client==3.1.0
from notion_client import Client
import os

notion = Client(auth=os.environ["NOTION_TOKEN"], notion_version="2026-03-11")

db = notion.databases.retrieve(database_id=os.environ["NOTION_TASKS_DB_ID"])
data_source_id = db["data_sources"][0]["id"]

results = notion.data_sources.query(
    data_source_id=data_source_id,
    filter={"property": "Status", "status": {"equals": "Done"}},
)
for page in results["results"]:
    print(page["id"])

Pagination and the 10,000-row cap

Every list or query endpoint returns results, has_more, and next_cursor. Send start_cursor and page_size (max 100). Pass next_cursor back verbatim; cursors are opaque. The SDK has two families of helpers:

Helper Use
iteratePaginatedAPI(fn, args) / collectPaginatedAPI(fn, args) Any paginated method (search, blocks.children.list, users.list, comments.list, dataSources.query)
iterateAllDataSourceRows(notion, args) / collectAllDataSourceRows(notion, args) Data sources that may exceed 10,000 rows. A single query stops there even with paging; these helpers window by created_time and de-duplicate (SDK ≥ 5.23.0)
import { Client, iteratePaginatedAPI, iterateAllDataSourceRows } from "@notionhq/client";

const notion = new Client({ auth: process.env.NOTION_TOKEN, notionVersion: "2026-03-11" });

for await (const block of iteratePaginatedAPI(notion.blocks.children.list, {
  block_id: process.env.NOTION_DOCS_PAGE_ID!,
})) {
  console.log(block.id);
}
for await (const row of iterateAllDataSourceRows(notion, {
  data_source_id: process.env.NOTION_DATA_SOURCE_ID!,
})) {
  console.log(row.id);
}

Rate limits and size limits

Limit Value (2026-10-20)
Per connection 180 requests/min (about 3/s) on Free and Plus; 600 requests/min (about 10/s) on Business and Enterprise. Fixed 60 s window, burstable. Retry-After is 60 s or less
Per workspace Shared by all of the workspace's connections and scaled to the plan; Retry-After can exceed a minute
Per endpoint Some endpoints have their own limit (rate_limit_reason: public_api_endpoint_rate_limit)
Payload 1,000 block elements and 500 KB per request; arrays of 100 elements; rich-text content 2,000 chars; URL 2,000; relation/people/multi-select 100 per request

How 429s work:

Writes that time out. A 503 can mean the write was saved. Read additional_data.retry_guidance and committed_resource_id before you retry. Markdown page writes return 504 gateway_timeout instead, and that doesn't mean the write was undone either.

Free-plan block limit through the API (from September 2026). Free workspaces with 2 or more members have a lifetime limit of 1,000 blocks. After the 3-day grace period ends, any API write that creates blocks returns 403 restricted_resource with additional_data.block_limit: "block_creation". The limit applies to internal connections and selected-workspace OAuth connections, but not to PATs or any-workspace OAuth. Retrying won't help; the workspace has to upgrade.


File uploads

Mode When Steps
single_part (default) ≤ 20 MiB fileUploads.create → fileUploads.send({ file }) → attach
multi_part > 20 MiB (paid workspaces) create({ mode: "multi_part", number_of_parts, filename }) → send each 5–20 MiB part with part_number (10 MiB recommended; the last part can be smaller) → complete → attach
external_url File already at a public HTTPS URL create({ mode: "external_url", external_url, filename }) → poll retrieve until uploaded

See examples/file-upload.ts (type-checked against 5.27.1).


Webhooks (with signature verification)

  1. In the Developer portal, open your connection → Webhooks → Create a subscription. Enter a public HTTPS URL (ngrok or a preview deploy in development) and choose the event types. Pick the subscription API version; 2026-03-11 payloads are identical to 2025-09-03.
  2. Notion POSTs a one-time { "verification_token": "…" }. Paste it into Verify in the portal and store it as a secret.
  3. Every event carries X-Notion-Signature: sha256=<hex>, an HMAC-SHA256 of the raw body keyed with that token. Verify it before doing anything else:
import { verifyWebhookSignature } from "@notionhq/client"; // SDK >= 5.23.0

export async function POST(request: Request): Promise<Response> {
  const rawBody = await request.text(); // raw bytes, not re-serialized JSON
  const ok = await verifyWebhookSignature({
    body: rawBody,
    signature: request.headers.get("x-notion-signature"),
    verificationToken: process.env.NOTION_WEBHOOK_VERIFICATION_TOKEN!,
  });
  if (!ok) return new Response("invalid signature", { status: 401 });
  // enqueue JSON.parse(rawBody), then return quickly
  return new Response(null, { status: 200 });
}

signWebhookPayload() generates signatures for tests. The helper works on Node 18+, Bun, Deno, Cloudflare Workers, and Vercel Edge. The full handler, including the handshake, is in examples/webhook-route.ts.

Event families:

Delivery rules:


Notion AI, Custom Agents, Workers — what matters to developers

Pricing (API-relevant, notion.com/pricing, 2026-10-20)

Plan Price What matters for the API
Free $0 Public API and webhooks included. 180 req/min per connection. 1,000-block lifetime limit for 2+ member workspaces, enforced through the API. 5 MB file uploads
Plus $10 per seat/month Unlimited blocks; uploads up to about 5 GB; Notion AI trial only; 180 req/min
Business $20 per seat/month 600 req/min; Notion Agent, Custom Agents, Workers (beta), Enterprise Search (beta); 1,500 Standard + 500 Select AI credits per seat per month; multi-source SQL in MCP
Enterprise Custom Everything in Business plus zero data retention with LLM providers, SCIM, audit log/SIEM, Admin API, MCP client allow-listing

Extra AI usage is bought as Notion credits. The pricing page lists per-seat monthly prices but doesn't say whether they're annual-billing rates, so confirm in checkout before you quote a customer.


Environment Variables

Secrets (store in the vault / .env.local, server-side only):

NOTION_TOKEN=ntn_...                         # internal connection token or PAT
NOTION_WEBHOOK_VERIFICATION_TOKEN=secret_... # from the webhook verification handshake
NOTION_OAUTH_CLIENT_SECRET=...               # public connections only

Non-secret settings (plain config):

Variable Purpose
NOTION_OAUTH_CLIENT_ID Public connection client ID
NOTION_OAUTH_REDIRECT_URI OAuth redirect (HTTPS)
NOTION_TASKS_DB_ID Task tracker database ID (container)
NOTION_DATA_SOURCE_ID Data source inside that database (query/create target)
NOTION_DOCS_PAGE_ID Docs root page
NOTION_CHANGELOG_PAGE_ID Changelog page used by the hook below
NOTION_SPRINT_DB_ID Sprint planning database

Take IDs from id fields, not from URLs. Record links moved from www.notion.so/{id} to app.notion.com/p/{id} in June 2026, and Notion says the format may change again.


Automation Workflows

Claude Code hook: append feat: commits to a changelog page

.claude/settings.json:

{
  "hooks": {
    "Stop": [
      { "hooks": [{ "type": "command", "command": "node scripts/notion-update-docs.mjs" }] }
    ]
  }
}

scripts/notion-update-docs.mjs:

import { Client } from "@notionhq/client";
import { execFileSync } from "node:child_process";

const notion = new Client({ auth: process.env.NOTION_TOKEN, notionVersion: "2026-03-11" });

const commitMsg = execFileSync("git", ["log", "-1", "--pretty=%B"]).toString().trim();
if (!commitMsg.startsWith("feat:")) process.exit(0);

await notion.pages.updateMarkdown({
  page_id: process.env.NOTION_CHANGELOG_PAGE_ID,
  type: "insert_content",
  insert_content: {
    content: `- [${new Date().toISOString().slice(0, 10)}] ${commitMsg}\n`,
    position: { type: "start" },
  },
});

Slash command: create a task

.claude/commands/notion-task.md:

Create a new task in the Notion tasks data source for: $ARGUMENTS

Use the Notion MCP (notion-create-pages) with:
- Name: $ARGUMENTS
- Status: Not started
- Priority: Medium
- Source: "Claude Code"

Report the URL of the created Notion page.

CI: record a release on deploy

# .github/workflows/notion-update.yml
name: Update Notion on Deploy
on:
  workflow_run:
    workflows: ["Deploy to Production"]
    types: [completed]

jobs:
  update-notion:
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    steps:
      - uses: actions/setup-node@v4   # pin to a full commit SHA in real workflows
        with: { node-version: '22' }
      - run: npm install @notionhq/client@5.27.1
      - name: Update Notion
        env:
          NOTION_TOKEN: ${{ secrets.NOTION_TOKEN }}
          NOTION_SPRINT_DB_ID: ${{ vars.NOTION_SPRINT_DB_ID }}
          SHA: ${{ github.sha }}
        run: |
          node --input-type=module -e "
          import { Client } from '@notionhq/client';
          const notion = new Client({ auth: process.env.NOTION_TOKEN, notionVersion: '2026-03-11' });
          const db = await notion.databases.retrieve({ database_id: process.env.NOTION_SPRINT_DB_ID });
          await notion.pages.create({
            parent: { type: 'data_source_id', data_source_id: db.data_sources[0].id },
            properties: {
              Name: { title: [{ text: { content: 'Deployed: ' + process.env.SHA } }] },
              Date: { date: { start: new Date().toISOString().slice(0, 10) } },
            },
          });
          "

Common Use Cases

Use case Approach
Task tracking MCP notion-create-pages into the tasks data source
Sprint review MCP notion-query-data-sources (mode: "view" on a saved view is free on every plan)
Auto-changelog Hook → pages.updateMarkdown insert_content
Knowledge-base search MCP notion-ai-search (Notion AI) or notion-search (keyword)
React to edits Webhook subscription → verify → queue → re-fetch
Import assets File Upload API (external_url for migrations)
Pull external data into Notion Notion Worker sync (beta)

Troubleshooting

Issue Fix
401 unauthorized Bad or expired token. PATs expire, and admins can revoke them or change the PAT policy
404 object_not_found Internal connection not shared with the page (••• → Connections or the portal's Content access)
databases.query is not a function SDK v5: use dataSources.query({ data_source_id })
archived / after ignored or rejected You're on 2026-03-11: use in_trash, and position: { type: "after_block", after_block: { id } }. The SDK logs a warning for unknown params
Only 10,000 rows come back Use collectAllDataSourceRows / iterateAllDataSourceRows
403 restricted_resource with block_limit Free multi-member workspace is out of blocks. Upgrade; retrying won't help
429 rate_limited Honor Retry-After / additional_data.retry_after; check rate_limit_reason (workspace-shared vs per-connection)
503 on a write Check additional_data.retry_guidance / committed_resource_id; the write may already be saved
Webhook signature never matches Verify the raw body, not JSON.stringify(await req.json())
Formula or rollup is type: "unsupported" Too many related pages or nested formulas; treat the value as unavailable

codeAmani notes

Official docs: