Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

nextjs-server-client-components

БесплатноБез исполняемых скриптовНе проверен

Guide for choosing between Server Components and Client Components in Next.js App Router. CRITICAL for useSearchParams (requires Suspense + 'use client')…

wsimmondsот wsimmonds★ 116 звёзд на GitHub26 установок в других каталогах

Об этом скилле

Next.js Server Components vs Client Components

Overview

Provide comprehensive guidance for choosing between Server Components and Client Components in Next.js App Router, including cookie/header access, searchParams handling, pathname routing, and React's 'use' API for promise unwrapping.

TypeScript: NEVER Use any Type

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

❌ WRONG:

function handleSubmit(e: any) { ... }
const data: any[] = [];

✅ CORRECT:

function handleSubmit(e: React.FormEvent<HTMLFormElement>) { ... }
const data: string[] = [];

Common Next.js Type Patterns

// Page props
function Page({ params }: { params: { slug: string } }) { ... }
function Page({ searchParams }: { searchParams: { [key: string]: string | string[] | undefined } }) { ... }

// Form events
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { ... }
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { ... }

// Server actions
async function myAction(formData: FormData) { ... }

When to Use This Skill

Use this skill when:

  • Deciding whether to use Server or Client Components
  • Accessing cookies, headers, or other server-side data
  • Working with searchParams or route parameters
  • Needing pathname or routing information
  • Unwrapping promises with React 'use' API
  • Debugging 'use client' boundary issues
  • Optimizing component rendering strategy

Core Decision: Server vs Client Components

Default: Server Components

All components in the App Router are Server Components by default. No directive needed.

// app/components/ProductList.tsx
// This is a Server Component (default)
export default async function ProductList() {
  const products = await fetch('https://api.example.com/products');
  const data = await products.json();

  return (
    <ul>
      {data.map(product => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

When to use Server Components:

  • Fetching data from APIs or databases
  • Accessing backend resources (environment variables, file system)
  • Processing sensitive information (API keys, tokens)
  • Reducing client-side JavaScript bundle
  • SEO-critical content rendering
  • Static or infrequently changing content

Benefits:

  • Zero client-side JavaScript by default
  • Direct database/API access
  • Secure handling of secrets
  • Automatic code splitting
  • Better initial page load performance
  • Reduced bundle size

Client Components: 'use client'

Add 'use client' directive at the top of a file to make it a Client Component.

// app/components/Counter.tsx
'use client';

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

When to use Client Components:

  • Need React hooks (useState, useEffect, useContext, etc.)
  • Event handlers (onClick, onChange, onSubmit, etc.)
  • Browser-only APIs (window, localStorage, navigator)
  • Third-party libraries requiring browser environment
  • Interactive UI elements (modals, dropdowns, forms)
  • Real-time features (WebSocket, animations)

Requirements for Client Components:

  • Must have 'use client' directive at top of file
  • Cannot use async/await directly in component
  • Cannot access server-only APIs (cookies, headers)
  • All imported components become Client Components

⚠️ CRITICAL: Server Components NEVER Need 'use client'

Server Components are the DEFAULT. DO NOT add 'use client' unless you specifically need client-side features.

✅ CORRECT - Server Component with Navigation:

// app/page.tsx - Server Component (NO 'use client' needed!)
import Link from 'next/link';
import { redirect } from 'next/navigation';

export default async function Page() {
  // Server components can be async
  const data = await fetchData();

  if (!data) {
    redirect('/login');  // Server-side redirect
  }

  return (
    <div>
      <Link href="/dashboard">Go to Dashboard</Link>
      <p>{data.content}</p>
    </div>
  );
}

❌ WRONG - Adding 'use client' to Server Component:

// app/page.tsx
'use client';  // ❌ WRONG! Don't add this to server components!

export default async function Page() {  // ❌ Will fail - async client components not allowed
  const data = await fetchData();
  return <div>{data.content}</div>;
}

Server Navigation Methods (NO 'use client' needed):

  • <Link> component from next/link
  • redirect() function from next/navigation
  • Server Actions (see Advanced Routing skill)

Client Navigation Methods (REQUIRES 'use client'):

  • useRouter() hook from next/navigation
  • usePathname() hook
  • useSearchParams() hook (also requires Suspense)

Server Component Patterns

Accessing Cookies

Use `next

Полный SKILL.md на GitHub

Установить nextjs-server-client-components в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Write
Edit
Glob
Grep
Bash

FAQ

Что делает скилл nextjs-server-client-components?

Guide for choosing between Server Components and Client Components in Next.js App Router. CRITICAL for useSearchParams (requires Suspense + 'use client'), navigation (Link, redirect, useRouter), cookies/headers access, and 'use client' directive. Activates when prompt mentions useSearchParams, Suspense, navigation, routing, Link component, redirect, pathname, searchParams, cookies, headers, async components, or 'use client'. Essential for avoiding mixing server/client APIs.

Как установить скилл nextjs-server-client-components?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл nextjs-server-client-components запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

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

Сравнить nextjs-server-client-components с