Nextjs Dynamic Routes Params 标志

Nextjs Dynamic Routes Params

社区
wsimmonds
nextjs-dynamic-routes-params

Guide for Next.js App Router dynamic routes and pathname parameters. Use when building pages that depend on URL segments (IDs, slugs, nested paths), accessing the `params` prop, or fetching resources by identifier. Helps avoid over-nesting by defaulting to the simplest route structure (e.g., `app/[id]` instead of `app/products/[id]` unless the URL calls for it).

Add to TypingMind

概览

发布者wsimmonds
代码仓库claude-nextjs-skills
技能名称nextjs-dynamic-routes-params
星标数
108
复刻数
22
附带文件
仅含指令
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 wsimmonds 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Nextjs Dynamic Routes Params AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/wsimmonds/claude-nextjs-skills/tree/main/nextjs-dynamic-routes-params
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wsimmonds/claude-nextjs-skills.git /tmp/claude-nextjs-skills
mkdir -p .claude/skills
cp -r /tmp/claude-nextjs-skills/nextjs-dynamic-routes-params .claude/skills/nextjs-dynamic-routes-params
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Nextjs Dynamic Routes Params,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Nextjs Dynamic Routes Params。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Nextjs Dynamic Routes Params 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Next.js Dynamic Routes and Pathname Parameters

When to Use This Skill

Use this skill when:

  • Creating dynamic route segments (e.g., blog/[slug], users/[id])
  • Accessing URL pathname parameters in Server or Client Components
  • Building pages that fetch data based on route parameters
  • Implementing catch-all or optional catch-all routes
  • Working with the params prop in page.tsx, layout.tsx, or route.ts

⚠️ RECOGNIZING WHEN YOU NEED DYNAMIC ROUTES

Look for requirements that tie data to the URL path.

Create a dynamic segment ([param]) whenever the UI depends on part of the pathname. Typical signals include:

  • Details pages that reference “the item’s ID/slug from the URL”
  • Copy that calls out path segments (e.g., /products/{id}, /blog/{slug})
  • Requirements to fetch data “based on whichever resource is being visited”
  • Navigation flows where one page links to /something/{identifier}

✅ Dynamic route response

Requirement: display product information based on whichever ID appears in the URL
Implementation: app/[id]/page.tsx
Access parameter with: const { id } = await params;

❌ Static-page response

Implementation: app/page.tsx  ← cannot access per-path identifiers

Example requirements that lead to dynamic routes

  1. “Show a product page that loads whichever product ID appears in the URL” → app/[id]/page.tsx or app/products/[id]/page.tsx
  2. “Render a blog article based on its slug” → app/blog/[slug]/page.tsx or app/[slug]/page.tsx
  3. “Support nested docs such as /docs/getting-started/installation” → app/docs/[...slug]/page.tsx

Core rule: If data varies with a URL segment, the folder name needs matching brackets.

⚠️ CRITICAL: Avoid Over-Engineering Route Structure

MOST COMMON MISTAKE: Adding unnecessary nesting to routes.

Default Rule: When creating a dynamic route, use app/[id]/page.tsx or app/[slug]/page.tsx unless:

  • The URL structure is explicitly specified (e.g., "create route at /products/[id]")
  • You're building multiple resource types that need namespacing
  • The requirements clearly show a nested URL structure

Do NOT infer nesting from resource names:

  • "Fetch a product by ID" → app/[id]/page.tsx ✅ (not app/products/[id])
  • "Show user profile" → app/[userId]/page.tsx ✅ (not app/users/[userId])
  • "Display blog post" → app/[slug]/page.tsx ✅ (not app/blog/[slug])

Only nest when explicitly told:

  • "Create a route at /blog/[slug]" → app/blog/[slug]/page.tsx ✅
  • "Products should be at /products/[id]" → app/products/[id]/page.tsx ✅

Core Concepts

Dynamic Route Syntax

Next.js uses folder names with square brackets to create dynamic route segments:

app/
├── [id]/page.tsx              # Matches /123, /abc, etc.
├── blog/[slug]/page.tsx       # Matches /blog/hello-world
├── shop/[category]/[id]/page.tsx  # Matches /shop/electronics/123
└── docs/[...slug]/page.tsx    # Matches /docs/a, /docs/a/b, /docs/a/b/c

Key Principle: The folder structure IS the route structure.

Route Structure Decision Tree

CRITICAL RULE: Do NOT infer route structure from resource type names!

Just because you're fetching a "product" or "user" doesn't mean you need /products/[id] or /users/[id]. Unless explicitly told otherwise, prefer the simplest structure.

When deciding on route structure:

  1. Top-level dynamic route (app/[id]/page.tsx)

    • DEFAULT CHOICE - Use this unless specifically told otherwise
    • Use when the resource IS the primary entity
    • Use when only ID-based routing is needed
    • Examples: /123 for any resource, /abc-def for slugs
    • Pattern: The ID/slug is the only identifier needed
    • When in doubt, choose this!
  2. Nested dynamic route (app/category/[id]/page.tsx)

    • ONLY use when explicitly required by the URL structure
    • Use when you're told "create a /products/[id] route"
    • Use when the URL itself needs the category prefix
    • Examples: /products/123, /blog/my-post (when specified)
    • Pattern: Category + identifier (when both are required)
  3. Multi-segment dynamic (app/[cat]/[id]/page.tsx)

    • Use when hierarchy matters
    • Examples: /shop/electronics/123
    • Pattern: Multiple levels of categorization

⚠️ COMMON MISTAKE: Creating app/products/[id]/page.tsx when you should create app/[id]/page.tsx

❌ WRONG: "Fetch a product by ID" → app/products/[id]/page.tsx ✅ CORRECT: "Fetch a product by ID" → app/[id]/page.tsx

❌ WRONG: "Create a dynamic route for users" → app/users/[userId]/page.tsx ✅ CORRECT: "Create a dynamic route for users" → app/[userId]/page.tsx

Only add the category prefix when:

  • The requirement explicitly says "at /products/..." or similar
  • You're building multiple resource types that need namespacing
  • The URL structure is specified in requirements

Accessing Pathname Parameters

In Server Components (page.tsx, layout.tsx)

CRITICAL: In Next.js 15+, params is a Promise and must be awaited!

typescript
// ✅ CORRECT - Next.js 15+
export default async function ProductPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  const product = await fetch(`https://api.example.com/products/${id}`)
    .then(res => res.json());

  return <div>{product.name}</div>;
}
typescript
// ❌ WRONG - Treating params as synchronous object (Next.js 15+)
export default async function ProductPage({
  params,
}: {
  params: { id: string };  // Missing Promise wrapper
}) {
  const product = await fetch(`https://api.example.com/products/${params.id}`);
  // This will fail because params is a Promise!
}

For Next.js 14 and earlier:

typescript
// Next.js 14 - params is synchronous
export default async function ProductPage({
  params,
}: {
  params: { id: string };
}) {
  const product = await fetch(`https://api.example.com/products/${params.id}`)
    .then(res => res.json());

  return <div>{product.name}</div>;
}

In Route Handlers (route.ts)

typescript
// app/api/products/[id]/route.ts
export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;

  const product = await db.products.findById(id);
  return Response.json(product);
}

In Client Components

You CANNOT access params directly in Client Components. Instead:

  1. Use useParams() hook:
typescript
'use client';

import { useParams } from 'next/navigation';

export function ProductClient() {
  const params = useParams<{ id: string }>();
  const id = params.id;

  // Use the id...
}
  1. Pass params from Server Component:
typescript
// app/products/[id]/page.tsx (Server Component)
export default async function ProductPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  return <ProductClient productId={id} />;
}

// components/ProductClient.tsx
'use client';

export function ProductClient({ productId }: { productId: string }) {
  // Use productId...
}

Common Patterns

Pattern 1: Simple ID-Based Page

typescript
// app/[id]/page.tsx - Top-level dynamic route
interface PageProps {
  params: Promise<{ id: string }>;
}

export default async function ItemPage({ params }: PageProps) {
  const { id } = await params;

  const item = await fetch(`https://api.example.com/items/${id}`)
    .then(res => res.json());

  return (
    <div>
      <h1>{item.title}</h1>
      <p>{item.description}</p>
    </div>
  );
}

Pattern 2: Blog Post with Slug

typescript
// app/blog/[slug]/page.tsx
interface PageProps {
  params: Promise<{ slug: string }>;
}

export default async function BlogPost({ params }: PageProps) {
  const { slug } = await params;

  const post = await getPostBySlug(slug);

  return (
    <article>
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.content }} />
    </article>
  );
}

// Generate static params for SSG
export async function generateStaticParams() {
  const posts = await getAllPosts();

  return posts.map((post) => ({
    slug: post.slug,
  }));
}

Pattern 3: Nested Resources

typescript
// app/users/[userId]/posts/[postId]/page.tsx
interface PageProps {
  params: Promise<{
    userId: string;
    postId: string;
  }>;
}

export default async function UserPost({ params }: PageProps) {
  const { userId, postId } = await params;

  const [user, post] = await Promise.all([
    getUserById(userId),
    getPostById(postId),
  ]);

  return (
    <div>
      <h1>{post.title}</h1>
      <p>By {user.name}</p>
      <div>{post.content}</div>
    </div>
  );
}

Pattern 4: Catch-All Routes

typescript
// app/docs/[...slug]/page.tsx - Matches /docs/a, /docs/a/b, /docs/a/b/c
interface PageProps {
  params: Promise<{
    slug: string[];  // Array of path segments
  }>;
}

export default async function DocsPage({ params }: PageProps) {
  const { slug } = await params;
  const path = slug.join('/');

  const doc = await getDocByPath(path);

  return <div>{doc.content}</div>;
}
typescript
// app/shop/[[...slug]]/page.tsx - Optional catch-all
// Matches /shop, /shop/electronics, /shop/electronics/phones
interface PageProps {
  params: Promise<{
    slug?: string[];  // Optional array
  }>;
}

export default async function ShopPage({ params }: PageProps) {
  const { slug = [] } = await params;

  if (slug.length === 0) {
    return <ShopHomepage />;
  }

  return <CategoryPage category={slug.join('/')} />;
}

TypeScript Best Practices

Type Safety for Params

typescript
// Define params type separately for reusability
type ProductPageParams = { id: string };

interface ProductPageProps {
  params: Promise<ProductPageParams>;
}

export default async function ProductPage({ params }: ProductPageProps) {
  const { id } = await params;
  // id is typed as string
}

// Reuse in generateMetadata
export async function generateMetadata({ params }: ProductPageProps) {
  const { id } = await params;
  const product = await getProduct(id);
  return { title: product.name };
}

Multiple Dynamic Segments

typescript
type PostPageParams = {
  category: string;
  slug: string;
};

interface PostPageProps {
  params: Promise<PostPageParams>;
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}

export default async function PostPage({ params, searchParams }: PostPageProps) {
  const { category, slug } = await params;
  const { view } = await searchParams;

  // All properly typed
}

Common Pitfalls and Solutions

Pitfall 1: Forgetting params is a Promise (Next.js 15+)

typescript
// ❌ WRONG
export default async function Page({ params }: { params: { id: string } }) {
  const product = await getProduct(params.id);  // Error: params is Promise
}

// ✅ CORRECT
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const product = await getProduct(id);
}

Pitfall 2: Using params in Client Components without useParams

typescript
// ❌ WRONG - params prop doesn't exist in Client Components
'use client';

export default function ClientPage({ params }) {  // undefined!
  return <div>{params.id}</div>;
}

// ✅ CORRECT
'use client';
import { useParams } from 'next/navigation';

export default function ClientPage() {
  const params = useParams<{ id: string }>();
  return <div>{params.id}</div>;
}

Pitfall 3: Over-nesting Routes

typescript
// ❌ UNNECESSARY NESTING
// app/products/product/[id]/page.tsx
// URL: /products/product/123

// ✅ SIMPLER
// app/products/[id]/page.tsx
// URL: /products/123

// OR even simpler if product is the main resource:
// app/[id]/page.tsx
// URL: /123

Pitfall 4: Not Handling Invalid IDs

typescript
// ✅ ROBUST
export default async function ProductPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  const product = await fetch(`https://api.example.com/products/${id}`)
    .then(res => {
      if (!res.ok) throw new Error('Product not found');
      return res.json();
    });

  if (!product) {
    notFound();  // Shows 404 page
  }

  return <div>{product.name}</div>;
}

Decision Guide

When you need to create a dynamic route, ask:

  1. What's the URL structure?

    • Single ID: [id]
    • Category + ID: category/[id]
    • Hierarchical: [category]/[id]
    • Flexible paths: [...slug]
  2. Is this a Server or Client Component?

    • Server: Use params prop (await it in Next.js 15+)
    • Client: Use useParams() hook
  3. Do I need the simplest structure?

    • When in doubt, use fewer nesting levels
    • Top-level routes are simpler and more direct
  4. Am I on Next.js 15+?

    • Yes: params is Promise<{...}>
    • No: params is {...}

Examples: Real-World Scenarios

E-commerce Product Page

typescript
// app/products/[id]/page.tsx
import { notFound } from 'next/navigation';

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

async function getProduct(id: string): Promise<Product | null> {
  const res = await fetch(`https://api.example.com/products/${id}`, {
    next: { revalidate: 60 },  // Revalidate every 60s
  });

  if (!res.ok) return null;
  return res.json();
}

export default async function ProductPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const product = await getProduct(id);

  if (!product) {
    notFound();
  }

  return (
    <div>
      <h1>{product.name}</h1>
      <p>${product.price}</p>
      <p>{product.description}</p>
    </div>
  );
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const product = await getProduct(id);

  return {
    title: product?.name ?? 'Product Not Found',
    description: product?.description,
  };
}

Documentation Site with Nested Paths

typescript
// app/docs/[...slug]/page.tsx
interface DocPageProps {
  params: Promise<{ slug: string[] }>;
}

export default async function DocPage({ params }: DocPageProps) {
  const { slug } = await params;
  const path = slug.join('/');

  const doc = await getDocByPath(path);

  if (!doc) {
    notFound();
  }

  return (
    <article className="prose">
      <h1>{doc.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: doc.html }} />
    </article>
  );
}

export async function generateStaticParams() {
  const docs = await getAllDocs();

  return docs.map((doc) => ({
    slug: doc.path.split('/'),
  }));
}

Checklist for Dynamic Routes

Before implementing a dynamic route, verify:

  • Route structure is as simple as possible (default to top-level unless told otherwise)
  • Not inferring route nesting from resource type names
  • Route structure matches URL requirements (not over-nested)
  • params is typed as Promise<{...}> for Next.js 15+
  • params is awaited before accessing properties (Next.js 15+)
  • Error handling for invalid IDs/slugs (use notFound())
  • TypeScript types are properly defined
  • Using Server Component unless client interactivity needed
  • Consider generateStaticParams() for SSG if applicable
  • Metadata generation if SEO matters

Quick Reference

ScenarioRoute StructureParams Access
Single resource by IDapp/[id]/page.tsxconst { id } = await params
Category + resourceapp/category/[id]/page.tsxconst { id } = await params
Blog with slugsapp/blog/[slug]/page.tsxconst { slug } = await params
Nested resourcesapp/[cat]/[id]/page.tsxconst { cat, id } = await params
Flexible pathsapp/docs/[...slug]/page.tsxconst { slug } = await params (slug is array)
Optional pathsapp/[[...slug]]/page.tsxconst { slug = [] } = await params
Client ComponentUse useParams() hookconst params = useParams<{ id: string }>()

Remember: Dynamic routes in Next.js are file-system based. The folder structure with [brackets] creates the dynamic segments, and the params prop (or useParams() hook) provides access to those values.

常见问题

Nextjs Dynamic Routes Params AI 技能有什么作用?

Guide for Next.js App Router dynamic routes and pathname parameters. Use when building pages that depend on URL segments (IDs, slugs, nested paths), accessing the `params` prop, or fetching resources by identifier. Helps avoid over-nesting by defaulting to the simplest route structure (e.g., `app/[id]` instead of `app/products/[id]` unless the URL calls for it).

为什么在 TypingMind 中使用 Nextjs Dynamic Routes Params?

因为您只需安装一次,就能搭配任何模型使用。Nextjs Dynamic Routes Params 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Nextjs Dynamic Routes Params?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/wsimmonds/claude-nextjs-skills/tree/main/nextjs-dynamic-routes-params。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Nextjs Dynamic Routes Params?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Nextjs Dynamic Routes Params 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Nextjs Dynamic Routes Params 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Nextjs Dynamic Routes Params AI 技能免费吗?

是的。wsimmonds 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇