К основному содержанию
скилл CX Codex

next-best-practices · laguagu — скилл для Claude Code: установка и функции

Скилл next-best-practices для Claude Code подсказывает практики Next.js App Router при написании и проверке кода. Помогает разбирать ошибки гидратации, границы RSC и проблемы с данными.

MIT 286 установок ★ 74 обновлён 2026-11-14

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add laguagu/claude-code-nextjs-skills --skill next-best-practices -a claude-code
Открыть на GitHub

Что делает next-best-practices

Скилл помогает писать и проверять код для Next.js App Router с учётом соглашений файлов, асинхронных API, маршрутов и метаданных. Он охватывает границы Server и Client Components, загрузку изображений и шрифтов, сборку и работу с данными. Для нужной области скилл обращается к документации установленной версии Next.js и настройкам проекта.

Перед другими изменениями он сверяет версию Next.js с рекомендациями по безопасности. При обновлении учитывает изменения API и предлагает подходящие codemod-команды; проектные роутер, режим кэширования и менеджер пакетов сохраняет, если миграция не запрошена. Версия Next.js влияет на доступность API и исправлений безопасности.

После изменений скилл предлагает проверять код скриптами lint и typecheck проекта, выполнить production-сборку и проверить изменённый маршрут через next start. Одна dev-сборка не выявляет все ошибки prerender и Suspense.

Какие задачи решает

  • найти причины ошибок гидратации
  • проверить границы Server и Client Components
  • исправить асинхронную работу с параметрами маршрута
  • разобрать несовместимости после обновления Next.js
  • проверить обработчики маршрутов и кэширование

Примеры запросов агенту

  • Проверь этот маршрут Next.js на ошибки гидратации и границы RSC.
  • Обнови страницу блога с учётом версии Next.js в проекте.
  • Разбери ошибки сборки после обновления Next.js и предложи подходящий codemod.

Как установить next-best-practices

1Через Skills CLI (Vercel)

npx skills add laguagu/claude-code-nextjs-skills --skill next-best-practices -a claude-code

2Вручную: положить файлы

~/.claude/skills/next-best-practices/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/next-best-practices/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о next-best-practices

Как установить next-best-practices в Claude Code?

Выполни npx skills add laguagu/claude-code-nextjs-skills --skill next-best-practices -a claude-code. Файл скилла находится по пути ~/.claude/skills/next-best-practices/SKILL.md.

Что делает next-best-practices?

Скилл помогает писать и проверять код Next.js App Router: разбирает ошибки гидратации, RSC, асинхронные API и работу с данными. Он сверяется с документацией установленной версии Next.js.

Что меняется в Next.js 16 для параметров маршрута?

В Next.js 16 params, searchParams, cookies() и headers() возвращают промисы. Скилл учитывает это при проверке и изменении кода.

Исходный текст

SKILL.md · MIT
---
name: next-best-practices
description: Next.js App Router best practices covering file conventions, RSC boundaries, async APIs, data patterns, hydration errors, metadata, route handlers, image/font optimization, and bundling. Use when writing or reviewing Next.js code to prevent hydration errors, RSC violations, data waterfalls, and configuration mistakes.
---

# Next.js review and implementation

Read the installed `next` version and relevant `node_modules/next/dist/docs/`
pages before changing framework behavior. Those docs and project configuration
take precedence; use a matching online version/source tag when local docs are
unavailable. Next.js publishes workflow skills in vercel/next.js `skills/`.

Docs are bundled from 16.2; in a monorepo, read the app's own `next` package.
The nextjs.org links in these files have local equivalents with numbered
folders, so search by file name (`find node_modules/next/dist/docs -name proxy.md`).
`01-app/02-guides/upgrading/version-16.md` lists the breaking changes.
Per-error pages (`/docs/messages/*`) are only online; the dev/build output
carries the error's fix options.
Exact exports are also in `node_modules/next/{server,navigation,headers,cache}.d.ts`.

Before other work, compare the installed version with Next.js security
advisories and tell the user when it is affected. As of 2026-11-09 the patched
releases are 16.4.5 and 15.5.29. 16.0.0–16.4.0 and 15.x up to 15.5.27 have
critical RCEs: `use cache` functions returning typed arrays
(GHSA-673q-mjm6-r5xr, 16.x only, no workaround) and self-hosted image
optimization of SVGs on glibc Linux (GHSA-2464-fhr4-w9xw; interim fix: sharp
0.35.5+), plus a Server Actions DoS (GHSA-p3m5-59mp-jv5r); 16.4.1 and 15.5.28
fixed those. Seven medium advisories of 2026-11-03 remain through 16.4.4 and
15.5.28: cross-user `use cache` disclosure (GHSA-rhh4-g77r-r9qj and three more,
16.x only), cross-client response injection when self-hosted
(GHSA-pc58-hwjq-p385), an image-optimization SVG bypass and an Edge-route
cookie exposure. From 16.4,
`experimental.agentUpgrade` (default `'security'`) reminds during
`next dev`/`next build`; 16.3.x and older get no reminder.

## Next.js 16 changes older examples miss

- Sync request access is removed: `cookies()`, `headers()`, `draftMode()`,
  `params` (including image-metadata routes), `searchParams` and sitemap `id`
  are promises. `next typegen` generates global `PageProps<'/route'>`,
  `LayoutProps` and `RouteContext` types.
- `middleware.ts` is deprecated: `proxy.ts` exporting `proxy` (or default)
  runs on Node.js only and rejects a `runtime` option; code that needs Edge
  stays in `middleware.ts`. Codemod: `npx @next/codemod@latest middleware-to-proxy .`.
- Turbopack is the default for `dev` and `build`; a custom `webpack` config
  fails the build unless `--webpack` keeps it or explicit `--turbopack` ignores
  it. `next lint` is removed and
  `next build` no longer lints. `serverRuntimeConfig`/`publicRuntimeConfig`
  are removed.
- Every parallel-route slot needs `default.tsx`, or the build fails.
- `next/image`: `priority` is deprecated for `preload`; `qualities` defaults to
  `[75]` (other `quality` values are coerced); local `src` with a query string
  needs `images.localPatterns`; `images.domains` is deprecated for
  `remotePatterns`.
- `revalidateTag(tag)` is deprecated; pass a profile such as `'max'` or
  `{ expire: 0 }` for immediate expiry. `updateTag` and `refresh` are Server
  Action-only. Caching details: `cache-components`.

The params and proxy shapes, checked against next 16.3.8 (`next typegen`,
`tsc --noEmit`, `next build`):

```tsx
// app/blog/[slug]/page.tsx; PageProps is global after `next typegen` (or dev/build)
export async function generateStaticParams() {
  return [{ slug: 'hello' }] // cacheComponents: needed for this top-level await; never []
}

export default async function Page({ params }: PageProps<'/blog/[slug]'>) {
  const { slug } = await params // a Promise; sync access was removed in 16
  return <h1>{slug}</h1>
}

// proxy.ts, replacing middleware.ts: Node.js runtime, no `runtime` export
import { NextResponse, type NextRequest } from 'next/server'

export function proxy(request: NextRequest) {
  // Optimistic check only: authorize again where the data is read.
  if (request.cookies.has('session')) return NextResponse.next()
  return NextResponse.redirect(new URL('/login', request.url))
}

export const config = { matcher: ['/dashboard/:path*'] }
```

The `upgrade` codemod does not migrate synchronous request-API access; run
`next-async-request-api` separately when migrating that code. Use the project's
package runner and review the resulting types and runtime behavior.

For an authorized upgrade, `npx next@canary upgrade [app-dir] --agent=security`
(or `=latest`; experimental, documented from 16.4 in the installed
`02-guides/upgrading/agent-upgrade.md`) selects the target and prints its guides,
codemods and checks for the current agent; plain `next upgrade` runs the
interactive codemods.

Review the actual failure or feature, rather than applying every optimization.
Keep the project's router, caching mode, runtime and package manager unless
migration is requested.

## Read for the affected area

| Area | Local reference |
| --- | --- |
| Route files, groups, proxy | [File conventions](file-conventions.md) |
| Server/client imports and props | [RSC boundaries](rsc-boundaries.md), [directives](directives.md) |
| Params and request APIs | [Async APIs](async-patterns.md), [functions](functions.md) |
| Reads, mutations and APIs | [Data patterns](data-patterns.md), [Route Handlers](route-handlers.md) |
| Rendering and failures | [Suspense](suspense-boundaries.md), [hydration](hydration-error.md), [errors](error-handling.md) |
| Metadata and public discovery | [Metadata](metadata.md); `nextjs-seo` for an SEO audit |
| Assets and loading | [Images](image.md), [fonts](font.md), [scripts](scripts.md) |
| Package/runtime behavior | [Bundling](bundling.md), [runtime](runtime-selection.md) |
| Navigation slots/modals | [Parallel routes](parallel-routes.md) |
| Deployment/debugging | [Self-hosting](self-hosting.md), [diagnostics](debug-tricks.md) |

Use `cache-components` when that mode is enabled and relevant to the task.
Tag invalidation can also operate on fetch caches outside that mode.

Validate with the project's lint/typecheck scripts and a production build,
then exercise the changed route under `next start`. A dev render can
hide prerender/Suspense issues; a build cannot prove authorization, hydration,
freshness or cross-instance behavior. Report what was actually exercised.

© laguagu · MIT · laguagu/claude-code-nextjs-skills

Похожие скиллы

Все скиллы по теме «Фронтенд и UI» →

Сначала — next-best-practices от других авторов.

next-best-practices pedronauck Скилл next-best-practices для Claude Code и других агентов: набор правил Next.js по файловым конвенциям, границам RSC, async API, метаданным и обработке ошибок. Подключается автоматически при написании или ревью кода на Next.js. CX Codex +1 402установок nextjs-app-architecture aurorascharff Скилл nextjs-app-architecture задаёт единую архитектуру App Router в Next.js 16: страницы только компонуют, данные читают фичи. Пригодится при старте проекта и при разборе чужого кода. CX Codex +1 540установок nextjs-app-router-expert curiositech Скилл nextjs-app-router-expert помогает проектировать и отлаживать приложения на Next.js 14/15 с App Router. Пригодится при настройке маршрутов, Server Actions и загрузки данных. CX Codex +1 176установок cra-to-next-migration community Скилл cra-to-next-migration помогает перенести проекты с Create React App на Next.js 16+. Скилл переводит маршруты React Router в App Router, меняет переменные окружения и внедряет Server Components. CX Codex +1 960установок Next.js App taste f Промпт Next.js App taste для ChatGPT и Claude.ai задаёт прагматичные стандарты разработки на Next.js App Router. Правила направляют генерацию архитектуры роутов, серверных компонентов и валидации данных. GP ChatGPT ★ 178 201звёзд репо next-intl-app-router liuchiawei Скилл next-intl-app-router для Claude Code. Настраивает next-intl с локалью в пути: конфиг, прокси, навигация и файлы сообщений. Закрывает добавление второго языка в проект. CX Codex +1 619установок Next.js Expert официальный github Субагент Next.js Expert для GitHub Copilot проектирует и меняет приложения на Next.js 16 с App Router, Server Components и TypeScript. Решает задачи архитектуры и кода. CX Codex +1 ★ 41 430звёзд репо

Из того же набора13

Весь набор →
nextjs-seo Скилл nextjs-seo для Claude Code помогает внедрять SEO в Next.js App Router и проверять уже настроенные страницы. Включается для работы с метаданными, индексацией, структурированными данными и политикой обхода сайта. CX Codex +1 2 600установок openai-agents-sdk Помогает разрабатывать агентов на Python с OpenAI Agents SDK. Подключается к задачам с инструментами, передачей управления между агентами, сессиями и потоковой выдачей. CX Codex +1 2 500установок supabase-postgres-best-practices Скилл supabase-postgres-best-practices помогает агенту проектировать схемы и писать SQL с учётом правил Supabase для Postgres. Подключайте его до изменений базы и при разборе проблем с запросами, подключениями или RLS. CX Codex +1 146установок nextjs-shadcn Скилл nextjs-shadcn для Claude Code и Codex настраивает интерфейсы Next.js на базе shadcn/ui. Агент подключает его при сборке и редизайне страниц, компонентов и дизайн-систем. CX Codex +1 861установок postgres-semantic-search Скилл postgres-semantic-search для Claude Code настраивает поиск и извлечение данных в PostgreSQL. Помогает собрать семантический или гибридный поиск, оценить качество результатов и разобраться со слабыми совпадениями. CX Codex +1 227установок cache-components Скилл cache-components даёт экспертные советы по кэшированию компонентов и частичному предрендерингу в Next.js 16.4+. CX Codex +1 222установок ai-sdk-6 Скилл ai-sdk-6 для работы с проектами на Vercel AI SDK v6. Помогает строить агентов, чат-ботов, инструменты и потоки структурированного вывода, если кодовая база уже на версии 6. CX Codex +1 218установок ai-app Скилл ai-app для Claude Code настраивает фулстек-приложения на Next.js с AI SDK и shadcn/ui. Запускается при создании чат-ботов, панелей управления агентами и ИИ-интерфейсов. CX Codex +1 198установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой