integration-nextjs-app-router — скилл для Claude Code: установка
Скилл integration-nextjs-app-router настраивает аналитику PostHog в проектах на Next.js App Router по официальным четырём этапам интеграции без лишних правок в архитектуре.
MIT 328 установок ★ 80 обновлён 2026-10-24
npx skills add PostHog/skills --skill integration-nextjs-app-router -a claude-codeЧто делает integration-nextjs-app-router
Скилл ведёт интеграцию PostHog по пошаговому плану из четырёх этапов: от первичного подключения до правок и финальной проверки. Он требует хранить ключи только в переменных окружения и не переписывать существующую кодовую базу, а добавлять аналитику рядом.
Внутри заложены правила под архитектуру Next.js. Для версии 15.3 и выше агент настроит инициализацию в instrumentation-client.ts. Отслеживание событий выносится строго в обработчики действий пользователя, а не в хук useEffect. Для синхронизации пользователей между фронтендом и бэкендом скилл настраивает проброс заголовков X-POSTHOG-DISTINCT-ID и X-POSTHOG-SESSION-ID.
Ключи аналитики запрещено хардкодить прямо в коде, поэтому перед началом понадобятся переменные окружения с токенами проекта.
Какие задачи решает
- Добавить сбор событий PostHog в проект на Next.js App Router
- Настроить вызов фичефлагов через хуки useFeatureFlagEnabled и useFeatureFlagPayload
- Связать клиентские и серверные события через заголовки сессии и distinct_id
- Разместить трекинг ошибок на критических маршрутах и API
Примеры запросов агенту
- Подключи PostHog аналитику в наш Next.js App Router проект по шагам скилла.
- Настрой фичефлаг PostHog для страницы каталога через правильный хук без useEffect.
- Добавь идентификацию пользователя при входе и передай заголовки сессии на бэкенд.
Как установить integration-nextjs-app-router
1Через Skills CLI (Vercel)
npx skills add PostHog/skills --skill integration-nextjs-app-router -a claude-code2Вручную: положить файлы
~/.claude/skills/integration-nextjs-app-router/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/integration-nextjs-app-router/
1Через Skills CLI (Vercel)
npx skills add PostHog/skills --skill integration-nextjs-app-router -a codex2Вручную: положить файлы
.agents/skills/integration-nextjs-app-router/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add PostHog/skills --skill integration-nextjs-app-router -a cursor2Вручную: положить файлы
.cursor/skills/integration-nextjs-app-router/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install PostHog/skills skills/posthog/all/skills/integration-nextjs-app-router2Вручную: положить файлы
.github/skills/integration-nextjs-app-router/SKILL.md1Через Skills CLI (Vercel)
npx skills add PostHog/skills --skill integration-nextjs-app-router -a gemini-cli2Командой платформы
gemini skills install https://github.com/PostHog/skills --path skills/posthog/all/skills/integration-nextjs-app-routerВручную: положить файлы
.devin/skills/integration-nextjs-app-router/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add PostHog/skills --skill integration-nextjs-app-router -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы об integration-nextjs-app-router
Как установить integration-nextjs-app-router в Claude Code?
Выполните команду npx skills add PostHog/skills --skill integration-nextjs-app-router -a claude-code. Файл инструкции сохранится по пути ~/.claude/skills/integration-nextjs-app-router/SKILL.md.
Что делает скилл integration-nextjs-app-router?
Он инструктирует агента, как безопасно подключить аналитику PostHog к Next.js App Router, опираясь на официальные примеры и архитектурные правила без хардкода ключей.
Где инициализировать клиентский код в Next.js 15.3+?
Инструкция предписывает выполнять инициализацию в файле instrumentation-client.ts, чтобы избежать лишней сложности в компонентах.
Исходный текст
SKILL.md · MIT
--- name: integration-nextjs-app-router description: PostHog integration for Next.js App Router applications metadata: author: PostHog version: 1.9.4 --- # PostHog integration for Next.js App Router This skill helps you add PostHog analytics to Next.js App Router applications. ## Workflow Follow these steps in order to complete the integration: 1. `basic-integration-1.0-begin.md` - PostHog Setup - Begin ← **Start here** 2. `basic-integration-1.1-edit.md` - PostHog Setup - Edit 3. `basic-integration-1.2-revise.md` - PostHog Setup - Revise 4. `basic-integration-1.3-conclude.md` - PostHog Setup - Conclusion ## Reference files - `references/EXAMPLE.md` - Next.js App Router example project code - `references/next-js.md` - Next.js - docs - `references/identify-users.md` - Identify users - docs - `references/basic-integration-1.0-begin.md` - PostHog setup - begin - `references/basic-integration-1.1-edit.md` - PostHog setup - edit - `references/basic-integration-1.2-revise.md` - PostHog setup - revise - `references/basic-integration-1.3-conclude.md` - PostHog setup - conclusion The example project shows the target implementation pattern. Consult the documentation for API details. ## Key principles - **Environment variables**: Always use environment variables for PostHog keys. Never hardcode them. - **Minimal changes**: Add PostHog code alongside existing integrations. Don't replace or restructure existing code. - **Match the example**: Your implementation should follow the example project's patterns as closely as possible. ## Framework guidelines - For Next.js 15.3+, initialize PostHog in instrumentation-client.ts for the simplest setup - For feature flags, use useFeatureFlagEnabled() or useFeatureFlagPayload() hooks - they handle loading states and external sync automatically - Add analytics capture in event handlers where user actions occur, NOT in useEffect reacting to state changes - Do NOT use useEffect for data transformation - calculate derived values during render instead - Do NOT use useEffect to respond to user events - put that logic in the event handler itself - Do NOT use useEffect to chain state updates - calculate all related updates together in the event handler - Do NOT use useEffect to notify parent components - call the parent callback alongside setState in the event handler - To reset component state when a prop changes, pass the prop as the component's key instead of using useEffect - useEffect is ONLY for synchronizing with external systems (non-React widgets, browser APIs, network subscriptions) ## Identifying users Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` headers to maintain correlation. ## Error tracking Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries.
© PostHog · MIT · PostHog/skills