Развёртывание Node.js-приложений с Notion API на Vercel, Railway, Fly.io.

Звёзды2 926
Авторjeremylongshore

Установка

SKILL.md

Deploy Notion-Integrated Applications

Overview

Ship Node.js apps that talk to the Notion API to Vercel, Railway, or Fly.io. This skill covers environment variable management, the Notion client singleton pattern for serverless, rate limit handling at 3 req/sec, health check endpoints that verify Notion connectivity, and caching strategies to reduce API calls.

Deep code lives in references/ so this file stays a lean walkthrough. Read a reference when a step needs the full module, then Write or Edit the code into your project's src/.

Prerequisites

  • Node.js >= 18 project with @notionhq/client installed (npm i @notionhq/client)
  • Working Notion integration tested locally with a valid NOTION_TOKEN (starts with ntn_)
  • Platform CLI installed for your target: vercel, railway, or fly
  • Database or page IDs your integration needs access to

Authentication

Every request authenticates with an internal integration token (NOTION_TOKEN, prefix ntn_), created at notion.so/my-integrations and passed as auth to the client. In production the token is stored as an encrypted platform secret and injected at runtime — never committed to source. Store it with vercel env add NOTION_TOKEN production, railway variables set NOTION_TOKEN=..., or fly secrets set NOTION_TOKEN=.... Each database or page must also be explicitly shared with the integration in the Notion UI, or queries return ObjectNotFound.

Instructions

Step 1 — Prepare the application for production

Build a production entry point with four modules: a Notion client singleton, a rate limiter, a response cache, and a health check. The singleton is the essential piece — serverless containers recycle unpredictably, so a module-level client reuses connections across warm invocations instead of paying cold-start and rate-limit cost per request:

// src/notion-client.ts — singleton for serverless environments
import { Client, LogLevel } from '@notionhq/client';

let client: Client | null = null;

export function getNotionClient(): Client {
  if (!client) {
    if (!process.env.NOTION_TOKEN) {
      throw new Error('NOTION_TOKEN environment variable is not set');
    }
    client = new Client({
      auth: process.env.NOTION_TOKEN,
      logLevel: process.env.NODE_ENV === 'production' ? LogLevel.WARN : LogLevel.DEBUG,
      timeoutMs: 30_000,
    });
  }
  return client;
}

The rate limiter (token bucket for the 3 req/sec cap), the TTL response cache, and the healthCheck() function are provided in full — read production-ready application modules and copy each into src/.

Step 2 — Deploy to your target platform

Pick one platform. All three inject NOTION_TOKEN at runtime from an encrypted secret:

  • Vercel — serverless functions; best for Next.js apps, API routes, low-traffic webhooks (~200ms cold start).
  • Railway — always-on containers; best for long-running sync services and apps needing persistent state.
  • Fly.io — edge containers; best for global distribution and multi-region low-latency proxies.

Each path (secret setup, deploy command, and the framework-specific API-route wiring for the singleton, rate limiter, and cache) is in platform deployment paths.

Step 3 — Monitor Notion API errors in production

Add structured error logging so Notion-specific failures surface in your monitoring tool (Sentry, Datadog, or platform logs). The full classifyNotionError / logNotionError module — which maps every @notionhq/client error code to a retryability flag and an operator action, plus the API-route wiring — lives in production error monitoring. Copy it to src/notion-error-handler.ts and call logNotionError(error, context) from every catch block that touches the Notion API.

Key metrics to watch:

  • Rate limit hits (429 responses) per minute — alert if sustained above 5/min
  • Health check latency — alert if Notion latencyMs exceeds 2000ms
  • Auth failures (401/403) — alert immediately; means token rotation is needed
  • Cache hit ratio — target > 70% in steady state; a low ratio means wasted API calls

Output

This workflow produces:

  • Node.js application deployed to Vercel, Railway, or Fly.io
  • NOTION_TOKEN stored as an encrypted platform secret (never in source code)
  • Notion client singleton that reuses connections across serverless invocations
  • Rate limiter enforcing the 3 req/sec Notion API limit
  • In-memory response cache reducing redundant API calls
  • /health endpoint that verifies live Notion API connectivity
  • Structured error logging classifying Notion API failures by severity

Error Handling

IssueCauseSolution
NOTION_TOKEN is not set at runtimeSecret not configured for environmentRe-add secret: vercel env add / railway variables set / fly secrets set
Cold start timeout (> 10s)Large dependency tree or slow Notion handshakeSet min_machines_running: 1 (Fly.io) or use Railway always-on
429 Rate Limited in logsExceeding 3 req/sec sustainedIncrease cache TTL, batch queries, add request queuing
Health check returns degradedToken expired or Notion outageCheck status.notion.com; rotate token if 401
ObjectNotFound on database queryDatabase not shared with integrationOpen Notion, click Share, add the integration
Serverless function creates multiple clientsNot using singleton patternImport getNotionClient() from the shared module, not new Client()

Examples

Two complete, copy-ready examples live in full deployment examples:

  • Minimal Express server — a platform-agnostic server wiring the singleton, rate limiter, health check, and error handler into /health and /api/query routes.
  • Deploy script — a deploy.sh [vercel|railway|fly] that builds, sets the secret, deploys, and verifies the health endpoint.

Resources

  • Notion API Reference — official REST API docs
  • @notionhq/client npm — official SDK with built-in retry
  • Notion API Rate Limits — 3 req/sec per integration
  • Notion API Status — check during outages
  • Vercel Environment Variables — secret management
  • Railway Variables — encrypted secrets
  • Fly.io Secrets — runtime secret injection

Next Steps

  • Add webhook receivers with the notion-webhooks-events skill
  • Set up database sync pipelines with the notion-sync-databases skill
  • Implement page content extraction with the notion-extract-content skill

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: notion-deploy-integration](https://darkplay.ru/ai/skills/jeremylongshore-claude-code-plugins-plus-skills-notion-deploy-integration)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

plugin-devanthropics · Полный набор инструментов для разработки плагинов Claude Code. Включает 7 экспертных…
34 комп.
ruflo-metaharnessruvnet · Интеграция MetaHarness: доступ к score/genome/mint/mcp-scan/threat-model через навыки…
240 комп.
agentic-bundle-integration-apissickn33 · Установите набор редакционных навыков "Integration & APIs" для Claude Code.
49 917 ★
42crunch-api-security-testinganthropics · Автоматизация безопасности API прямо в Claude Code с помощью 42Crunch: аудит спецификаций…
100 комп.
agentforce-adlcanthropics · Жизненный цикл разработки агентов Agentforce — создание, поиск, скаффолдинг…
100 комп.
airtableanthropics · Airtable — слой базы данных и операций для ваших агентов в продукте, маркетинге…
100 комп.
amazon-location-serviceanthropics · Помогает разработчикам добавлять карты, поиск мест, геокодирование, маршрутизацию и…
100 комп.
apolloanthropics · Поиск клиентов, обогащение лидов, загрузка цепочек аутрича и аналитика продаж с Apollo.io…
100 комп.
appwriteanthropics · Инструменты Appwrite для Claude Code: навыки работы с SDK, MCP-серверы Appwrite и команды…
100 комп.
asanaanthropics · Интеграция с Asana для управления проектами. Создание и управление задачами, поиск…
100 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8