Token导航 LogoToken导航TokenDH.com
研究检索操作浏览器github未标认证来源可访问许可证需确认审计提醒

nextjs-app-routerNext.js 应用 router

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

14,183

周安装

603

GitHub Stars

229

下载量

4,969
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:nextjs-app-router(Next.js 应用 router)
来源仓库:https://github.com/giuseppe-trisciuoglio/developer-kit
仓库路径:skills/nextjs-app-router
安装命令:
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill nextjs-app-router
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill nextjs-app-router

简介

用于辅助前端页面和组件的开发与维护。

  • 适合生成或审查 React、Next.js 和 Tailwind 相关代码。
  • 需结合项目现有设计系统和路由方式使用。
  • 安装命令:npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill nextjs-app-router。
  • 涉及页面改动时应配合本地预览确认效果。

SKILL.md

Next.js App Router (Next.js 16+)

Build modern React applications using Next.js 16+ with App Router architecture.

Overview

This skill provides patterns for Server Components (default) and Client Components ("use client"), Server Actions for mutations and form handling, Route Handlers for API endpoints, explicit caching with "use cache" directive, parallel and intercepting routes, and Next.js 16 async APIs and proxy.ts.

When to Use

Activate when user requests involve:

  • "Create a Next.js 16 project", "Set up App Router"
  • "Server Component", "Client Component", "use client"
  • "Server Action", "form submission", "mutation"
  • "Route Handler", "API endpoint", "route.ts"
  • "use cache", "cacheLife", "cacheTag", "revalidation"
  • "parallel routes", "@slot", "intercepting routes"
  • "proxy.ts", "migrate from middleware.ts"
  • "layout.tsx", "page.tsx", "loading.tsx", "error.tsx", "not-found.tsx"
  • "generateMetadata", "next/image", "next/font"

Quick Reference

FilePurposeDirectivePurpose
page.tsxRoute page"use server"Server Action function
layout.tsxShared layout"use client"Client Component boundary
loading.tsxSuspense loading"use cache"Explicit caching (Next.js 16)
error.tsxError boundary
not-found.tsx404 page
route.tsAPI Route Handler
proxy.tsRouting boundary

Instructions

Create New Project

npx create-next-app@latest my-app --typescript --tailwind --app --turbopack

Server Component

Server Components are the default in App Router. They run on the server and can use async/await.

// app/users/page.tsx
async function getUsers() {
  const apiUrl = process.env.API_URL;
  const res = await fetch(`${apiUrl}/users`);
  return res.json();
}

export default async function UsersPage() {
  const users = await getUsers();
  return <main>{users.map(user => <UserCard key={user.id} user={user} />)}</main>;
}

Client Component

Add "use client" when using hooks, browser APIs, or event handlers.

"use client";

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>;
}

Server Action

Define actions in separate files with "use server" directive.

// app/actions.ts
"use server";

import { revalidatePath } from "next/cache";

export async function createUser(formData: FormData) {
  const name = formData.get("name") as string;
  const email = formData.get("email") as string;
  await db.user.create({ data: { name, email } });
  revalidatePath("/users");
}

Use with forms in Client Components:

"use client";

import { useActionState } from "react";
import { createUser } from "./actions";

export default function UserForm() {
  const [state, formAction, pending] = useActionState(createUser, {});
  return (
    <form action={formAction}>
      <input name="name" />
      <input name="email" type="email" />
      <button type="submit" disabled={pending}>{pending ? "Creating..." : "Create"}</button>
    </form>
  );
}

See references/server-actions.md for Zod validation, optimistic updates, and advanced patterns.

Configure Caching

Use "use cache" directive for explicit caching (Next.js 16+).

"use cache";

import { cacheLife, cacheTag } from "next/cache";

export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  cacheTag(`product-${id}`);
  cacheLife("hours");
  const product = await fetchProduct(id);
  return <ProductDetail product={product} />;
}

See references/caching-strategies.md for cache profiles, on-demand revalidation, and advanced patterns.

Route Handler

// app/api/users/route.ts
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  return NextResponse.json(await db.user.findMany());
}

export async function POST(request: NextRequest) {
  const body = await request.json();
  return NextResponse.json(await db.user.create({ data: body }), { status: 201 });
}

Dynamic segments use [param]:

// app/api/users/[id]/route.ts
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const user = await db.user.findUnique({ where: { id } });
  if (!user) return NextResponse.json({ error: "Not found" }, { status: 404 });
  return NextResponse.json(user);
}

Next.js 16 Async APIs

All Next.js APIs are async in version 16.

import { cookies, headers } from "next/headers";

export default async function Page() {
  const cookieStore = await cookies();
  const headersList = await headers();
  const session = cookieStore.get("session")?.value;
  const userAgent = headersList.get("user-agent");
  return <div>...</div>;
}

Params and searchParams are also Promise-based:

export default async function Page({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ sort?: string }>;
}) {
  const { slug } = await params;
  const { sort } = await searchParams;
  // ...
}

See references/nextjs16-migration.md for migration guide and proxy.ts configuration.

Parallel Routes

Use @folder convention for parallel route slots.

// app/dashboard/layout.tsx
export default function DashboardLayout({ children, team, analytics }: Record<string, React.ReactNode>) {
  return (
    <div>
      {children}
      <div className="grid grid-cols-2">{team}{analytics}</div>
    </div>
  );
}
// app/dashboard/@team/page.tsx
export default function TeamPage() { return <div>Team Section</div>; }

// app/dashboard/@analytics/page.tsx
export default function AnalyticsPage() { return <div>Analytics Section</div>; }

See references/routing-patterns.md for intercepting routes, route groups, and dynamic routes.

Best Practices

Server vs Client Decision:

  • Start with Server Component (default)
  • Use Client Component only for: React hooks (useState, useEffect), browser APIs (window, document), event handlers (onClick, onSubmit), or client-only libraries

Data Fetching:

  • Fetch in Server Components when possible
  • Use React's cache() for deduplication
  • Parallelize independent fetches
  • Add Suspense boundaries with loading.tsx

Performance Checklist:

  • Use loading.tsx for Suspense boundaries
  • Use next/image for optimized images
  • Use next/font for font optimization
  • Add error.tsx and not-found.tsx for error handling

Examples

Example 1: Blog Post Form with Server Action

Input: Create a form to submit blog posts with Zod validation

Output:

// app/blog/actions.ts
"use server";

import { z } from "zod";
import { revalidatePath } from "next/cache";

const schema = z.object({ title: z.string().min(5), content: z.string().min(10) });

export async function createPost(formData: FormData) {
  const parsed = schema.safeParse({ title: formData.get("title"), content: formData.get("content") });
  if (!parsed.success) return { errors: parsed.error.flatten().fieldErrors };
  await db.post.create({ data: parsed.data });
  revalidatePath("/blog");
  return { success: true };
}
// app/blog/new/page.tsx
"use client";

import { useActionState } from "react";
import { createPost } from "../actions";

export default function NewPostPage() {
  const [state, formAction, pending] = useActionState(createPost, {});
  return (
    <form action={formAction}>
      <input name="title" placeholder="Title" />
      {state.errors?.title && <span>{state.errors.title[0]}</span>}
      <textarea name="content" placeholder="Content" />
      {state.errors?.content && <span>{state.errors.content[0]}</span>}
      <button type="submit" disabled={pending}>{pending ? "Publishing..." : "Publish"}</button>
    </form>
  );
}

Example 2: Cached Product Page

Input: Create a cached product page with on-demand revalidation

Output:

// app/products/[id]/page.tsx
"use cache";

import { cacheLife, cacheTag } from "next/cache";

export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  cacheTag(`product-${id}`, "products");
  cacheLife("hours");
  const product = await db.product.findUnique({ where: { id } });
  if (!product) notFound();
  return <article><h1>{product.name}</h1><p>{product.description}</p></article>;
}
// app/api/revalidate/route.ts
import { revalidateTag } from "next/cache";
import { NextResponse } from "next/server";

export async function POST(request: Request) {
  const { tag } = await request.json();
  revalidateTag(tag);
  return NextResponse.json({ revalidated: true });
}

Example 3: Dashboard with Parallel Routes

Input: Create a dashboard with sidebar and stats areas

Output:

// app/dashboard/layout.tsx
export default function DashboardLayout({ children, sidebar, stats }: Record<string, React.ReactNode>) {
  return (
    <div className="flex">
      <aside className="w-64">{sidebar}</aside>
      <main className="flex-1"><div className="grid grid-cols-3">{stats}</div>{children}</main>
    </div>
  );
}
// app/dashboard/@sidebar/page.tsx
export default function Sidebar() { return <nav>{/* Navigation links */}</nav>; }

// app/dashboard/@stats/page.tsx
export default async function Stats() {
  const stats = await fetchStats();
  return <><div>Users: {stats.users}</div><div>Orders: {stats.orders}</div></>;
}

Constraints and Warnings

Constraints:

  • Server Components cannot use browser APIs or React hooks
  • Client Components cannot be async (no direct data fetching)
  • cookies(), headers(), draftMode() are async in Next.js 16
  • params and searchParams are Promise-based in Next.js 16
  • Server Actions must be defined with "use server" directive

Warnings:

  • Using await in a Client Component causes a build error
  • Accessing window or document in Server Components throws an error
  • Forgetting to await cookies() or headers() in Next.js 16 returns a Promise instead of the value
  • Server Actions without proper validation can expose the database to unauthorized access
  • External Data Fetching: Server Components that fetch() third-party URLs process untrusted content — always validate, sanitize, and type-check responses; use environment variables for API URLs rather than hardcoding them

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.82%
按下载量换算1,879

Claude

30.25%
按下载量换算1,503

Cursor

19.84%
按下载量换算986

Gemini CLI

8.99%
按下载量换算447

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills