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

nextjs-pathname-id-fetch — скилл для Claude Code

Скилл nextjs-pathname-id-fetch для Claude Code задаёт шаблон страницы Next.js: динамический сегмент, await params и fetch по идентификатору из URL.

MIT 296 установок ★ 115 обновлён 2025-10-24

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

Что делает nextjs-pathname-id-fetch

Скилл задаёт один маршрут: папка в квадратных скобках app/[id]/page.tsx и асинхронный серверный компонент внутри. Сегмент читается через const { id } = await params, дальше fetch по этому значению. Карточка товара, пост в блоге, профиль — шаги везде одинаковые.

Внутри SKILL.md: рабочий пример, вариант с [slug] и с двумя сегментами, чек-лист перед выкаткой. Отдельно перечислены типовые промахи: статичная папка app/id/, директива 'use client' на странице, которой нужен серверный fetch, забытый await params в Next.js 15+. Разрешённые инструменты — Read, Write, Edit, Glob, Grep, Bash.

Охват узкий намеренно. Catch-all [...slug], опциональные и многопараметрические маршруты отданы соседнему скиллу nextjs-dynamic-routes-params. С типами осторожно: в репозитории включено правило @typescript-eslint/no-explicit-any, поэтому any в типе ответа API уронит сборку.

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

  • собрать страницу товара, которая берёт ID прямо из адреса
  • вытащить slug из URL внутри серверного компонента
  • починить маршрут, отдающий одну и ту же запись на любом пути
  • убрать 'use client' со страницы, которой нужен fetch на сервере
  • протипить params как Promise после перехода на Next.js 15

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

  • Создай app/[id]/page.tsx, возьми id из params и подтяни товар из API.
  • Почему app/id/page.tsx не видит сегмент URL? Переделай на динамический маршрут.
  • Добавь обработку случая, когда fetch вернул не ok, на странице товара.

Как установить nextjs-pathname-id-fetch

1Через Skills CLI (Vercel)

npx skills add wsimmonds/claude-nextjs-skills --skill nextjs-pathname-id-fetch -a claude-code

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

~/.claude/skills/nextjs-pathname-id-fetch/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/nextjs-pathname-id-fetch/

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

Вопросы о nextjs-pathname-id-fetch

Как установить nextjs-pathname-id-fetch в Claude Code?

Выполни npx skills add wsimmonds/claude-nextjs-skills --skill nextjs-pathname-id-fetch -a claude-code. Файл появится по пути ~/.claude/skills/nextjs-pathname-id-fetch/SKILL.md.

Что делает nextjs-pathname-id-fetch?

Показывает, как связать динамический сегмент URL с загрузкой данных в серверном компоненте Next.js: папка [id], await params, fetch по идентификатору.

Чем он отличается от nextjs-dynamic-routes-params?

Тот скилл закрывает catch-all [...slug], опциональные сегменты и сложные многопараметрические схемы. Этот берёт простой случай: одна запись по одному ID из адреса.

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

SKILL.md · MIT
---
name: nextjs-pathname-id-fetch
description: Focused pattern for fetching data using URL parameters in Next.js. Covers creating dynamic routes ([id], [slug]) and accessing route parameters in server components to fetch data from APIs. Use when building pages that display individual items (product pages, blog posts, user profiles) based on a URL parameter. Complements nextjs-dynamic-routes-params with a simplified, common-case pattern.
allowed-tools: Read, Write, Edit, Glob, Grep, Bash
---

# Next.js: Pathname ID Fetch Pattern

## When This Pattern Applies

Use this pattern whenever a page needs to load data based on whatever identifier appears in the URL. Common scenarios include:
- Detail pages for products, posts, or users (`/products/{id}`, `/blog/{slug}`)
- Admin dashboards that drill into a selected resource (`/admin/orders/{orderId}`)
- Documentation or knowledge bases with nested paths (`/docs/getting-started/installation`)

If the requirement says the data should change depending on the current URL path, the route segment must be dynamic (e.g., `[id]`, `[slug]`, `[...slug]`).

## The Pattern

**✅ Recommended implementation**
```
1. Create a dynamic folder: app/[id]/page.tsx
2. Access the parameter: const { id } = await params;
3. Fetch data using that identifier
4. Render the requested information
```

**❌ Pitfall**
```
Using app/page.tsx for this scenario prevents access to per-path identifiers.
```

## Complete Implementation Example

```typescript
// app/[id]/page.tsx

// IMPORTANT: Server component (NO 'use client' needed!)
export default async function ProductPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  // Next.js 15+: params must be awaited
  const { id } = await params;

  // Fetch data using the ID from the URL
  const response = await fetch(`https://api.example.com/products/${id}`);
  const product = await response.json();

  // Return JSX with the fetched data
  return (
    <div>
      <h1>{product.name}</h1>
      <p>{product.description}</p>
      <p>Price: ${product.price}</p>
    </div>
  );
}
```

## File Structure

```
app/
└── [id]/                 ← Dynamic route folder with brackets
    └── page.tsx          ← Server component page
```

**URL Mapping:**
- `/123` → params = `{ id: '123' }`
- `/abc` → params = `{ id: 'abc' }`
- `/product-xyz` → params = `{ id: 'product-xyz' }`

## Key Rules

### 1. Folder Name MUST Use Brackets
```
✅ app/[id]/page.tsx
✅ app/[productId]/page.tsx
✅ app/[slug]/page.tsx
❌ app/id/page.tsx        (no brackets = static route)
❌ app/page.tsx            (can't access params here)
```

### 2. This is a Server Component (Default)
```typescript
// ✅ CORRECT - No 'use client' needed
export default async function Page({ params }) {
  const { id } = await params;
  const data = await fetch(`/api/${id}`);
  return <div>{data.name}</div>;
}

// ❌ WRONG - Don't add 'use client' for server components
'use client';  // ← Remove this!
export default async function Page({ params }) { ... }
```

### 3. Params Must Be Awaited (Next.js 15+)
```typescript
// ✅ CORRECT - Next.js 15+
export default async function Page({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;  // Must await
  // ...
}

// ⚠️ OLD (Next.js 14 and earlier - deprecated)
export default async function Page({
  params,
}: {
  params: { id: string };
}) {
  const { id } = params;  // No await needed in old versions
  // ...
}
```

### 4. Keep It Simple - Don't Over-Nest
```
✅ app/[id]/page.tsx              (simple, clean)
❌ app/products/[id]/page.tsx     (only if explicitly required!)
```

Unless requirements explicitly call for `/products/[id]`, keep the structure at the top level (`app/[id]/page.tsx`).

## TypeScript: NEVER Use `any` Type

This codebase has `@typescript-eslint/no-explicit-any` enabled. Using `any` will cause build failures.

```typescript
// ❌ WRONG
function processProduct(product: any) { ... }

// ✅ CORRECT - Define proper types
interface Product {
  id: string;
  name: string;
  price: number;
}

function processProduct(product: Product) { ... }

// ✅ ALSO CORRECT - Use unknown if type truly unknown
function processData(data: unknown) {
  // Type guard required before using
  if (typeof data === 'object' && data !== null) {
    // ...
  }
}
```

## Common Variations

### Different Parameter Names
```typescript
// app/[productId]/page.tsx
export default async function Page({
  params,
}: {
  params: Promise<{ productId: string }>;
}) {
  const { productId } = await params;
  // ...
}

// app/[slug]/page.tsx
export default async function Page({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  // ...
}
```

### Multiple Parameters
```typescript
// app/[category]/[id]/page.tsx
export default async function Page({
  params,
}: {
  params: Promise<{ category: string; id: string }>;
}) {
  const { category, id } = await params;
  const data = await fetch(`/api/${category}/${id}`);
  // ...
}
```

## Complete Working Example

```typescript
// app/[id]/page.tsx - Product detail page

interface Product {
  id: string;
  name: string;
  description: string;
  price: number;
  inStock: boolean;
}

export default async function ProductPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  // Get the ID from the URL
  const { id } = await params;

  // Fetch product data using the ID
  const response = await fetch(
    `https://api.example.com/products/${id}`,
    { cache: 'no-store' } // Always fresh data
  );

  if (!response.ok) {
    throw new Error('Failed to fetch product');
  }

  const product: Product = await response.json();

  // Render the product
  return (
    <div>
      <h1>{product.name}</h1>
      <p>{product.description}</p>

      <div>
        <strong>Price:</strong> ${product.price}
      </div>

      <div>
        <strong>Availability:</strong>{' '}
        {product.inStock ? 'In Stock' : 'Out of Stock'}
      </div>
    </div>
  );
}
```

## Quick Checklist

Before shipping a pathname-driven detail page, confirm:

- [ ] The route folder uses brackets (e.g., `app/[id]/page.tsx`)
- [ ] The component stays server-side (no `'use client'` needed)
- [ ] The `params` prop is typed as `Promise<{ id: string }>` for Next.js 15+
- [ ] You await the params and read the identifier safely
- [ ] Data fetching logic uses that identifier
- [ ] Rendering handles loading/error states appropriately
- [ ] Types are explicit—never fall back to `any`

## When to Use the Comprehensive Skill Instead

This micro-skill covers the simple "pathname ID fetch" pattern. Use the comprehensive `nextjs-dynamic-routes-params` skill for:
- Catch-all routes (`[...slug]`)
- Optional catch-all routes (`[[...slug]]`)
- Complex multi-parameter routing
- Advanced routing architectures
- Detailed routing decisions

For the simple case of "fetch data by ID from URL", this skill is all you need.

© wsimmonds · MIT · wsimmonds/claude-nextjs-skills

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

Все скиллы по теме «Фронтенд и UI» →
nextjs PyModel Внедряет стандарты Next.js 16 App Router. Направляет рефакторинг серверных компонентов, кэширования и маршрутов. CX Codex +1 621установок nextjs-cache-architecture mohamed-hossam1 Скилл nextjs-cache-architecture выстраивает архитектуру кеширования для Next.js 16+ App Router. Помогает внедрить директиву "use cache", собрать типизированный реестр тегов и настроить границы Suspense. CX Codex +1 5 100установок nextjs-app-router giuseppe-trisciuoglio Скилл nextjs-app-router для Claude Code помогает создавать приложения на Next.js 16+ с App Router. Подключается при работе с серверными компонентами, формами, API-маршрутами и кэшированием. CX Codex +1 4 100установок nextjs-best-practices davila7 Скилл nextjs-best-practices для Claude Code задаёт правила App Router: разделяет серверные и клиентские компоненты, настраивает кэширование и структуру маршрутов. CX Codex +1 1 785установок nextjs-typescript-tailwindcss-supabase Mindrally Скилл nextjs-typescript-tailwindcss-supabase задаёт агенту правила для Next.js 14, TypeScript, TailwindCSS и Supabase: серверные компоненты, обработка ошибок, читаемый код. CX Codex +1 1 400установок nextjs-15 gentleman-programming Скилл задаёт паттерны работы с App Router в Next.js 15: маршрутизацию, Server Actions, параллельную загрузку данных и настройку middleware. CX Codex +1 185установок

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

nextjs-app-router-fundamentals Скилл nextjs-app-router-fundamentals ведёт агента по Next.js App Router: перенос с Pages Router, вложенные layout, метаданные, динамические маршруты. Пригодится при переходе на app/. CX Codex +1 2 200установок nextjs-server-client-components Скилл nextjs-server-client-components помогает выбрать между Server и Client Components в Next.js App Router, настроить чтение cookies, работу с searchParams и избежать смешивания клиентских и серверных API. CX Codex +1 364установок vercel-ai-sdk Подсказывает агенту, как писать код на Vercel AI SDK v5: чат через useChat, стриминг, вызов инструментов, эмбеддинги. CX Codex +1 348установок nextjs-advanced-routing Скилл nextjs-advanced-routing для Claude Code и пяти других платформ, который учит агента работать с App Router: Route Handlers, Server Actions, Parallel Routes, Intercepting Routes и Suspense. CX Codex +1 336установок nextjs-client-cookie-pattern Скилл nextjs-client-cookie-pattern для Claude Code показывает, как выставить серверную куку из клиентского компонента Next.js через server action. Описывает куки для тем, авторизации и языковых настроек. CX Codex +1 326установок nextjs-use-search-params-suspense Скилл nextjs-use-search-params-suspense объясняет, как правильно читать параметры URL в клиентских компонентах Next.js: директива 'use client' плюс обёртка Suspense. CX Codex +1 313установок nextjs-server-navigation Скилл nextjs-server-navigation учит ИИ-агента настраивать навигацию в серверных компонентах Next.js через <Link> и redirect() без необоснованного добавления директивы 'use client'. CX Codex +1 305установок nextjs-dynamic-routes-params Скилл nextjs-dynamic-routes-params для Claude Code строит динамические сегменты App Router и читает params в Next.js 15+. Покрывает маршруты по ID или слагу. CX Codex +1 304установок

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

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