# Nextjs Skill

> This skill should be used when the user asks about Next.js, App Router, Pages Router, server components, server actions, Next.js routing, middleware, next.config.js, Vercel deployment, API routes, ISR, SSG, SSR, or any Next.js-related development. Trigger when the user mentions "nextjs", "next.js", "app router", "pages router", "server components", "server actions", "next/image", "next/font", "next/navigation", or building full-stack React applications with Next.js.

- Skill: `sirhamza/nextjs-skill` (Agent Skill)
- Install (CLI): `npx skillmds@latest add sirhamza/nextjs-skill`
- Raw SKILL.md: https://api.skillmd.com/api/skills/sirhamza/nextjs-skill/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Web & Frontend
- Author: SirHamza (https://skillmd.com/u/sirhamza)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/sirhamza/nextjs-skill

---


# Next.js Expert

## Overview

Advanced expertise in Next.js — from App Router and Server Components to full-stack deployment on Vercel and self-hosted environments. Covers both the modern App Router and legacy Pages Router patterns.

---

## 1. App Router (Next.js 13+)

- `app/` directory structure: layouts, pages, loading, error, not-found
- Nested layouts with `layout.tsx` — shared UI without re-rendering
- Route groups `(group)/` for organizing without affecting URL
- Dynamic segments: `[slug]`, `[...catchAll]`, `[[...optionalCatchAll]]`
- Parallel routes `@slot` and intercepting routes `(.)route`
- `page.tsx`, `layout.tsx`, `loading.tsx`, `error.tsx`, `not-found.tsx`, `template.tsx`
- `route.ts` API Route Handlers (GET, POST, PUT, DELETE, PATCH)
- Metadata API: `export const metadata`, `generateMetadata()`

---

## 2. Server Components & Client Components

- Server Components (default): no state, no hooks, async, direct DB/API access
- Client Components: `"use client"` directive, useState/useEffect allowed
- Composition patterns: wrap Client Components inside Server Components
- Passing Server Component output as `children` to Client Components
- `Suspense` boundaries for streaming and partial hydration
- Server-only imports: `server-only` package to prevent leaking
- `use()` hook for promise-based data in Client Components

---

## 3. Data Fetching

- `fetch()` with Next.js cache extensions: `cache: 'force-cache'` (SSG), `cache: 'no-store'` (SSR)
- `next: { revalidate: 60 }` for ISR (Incremental Static Regeneration)
- `next: { tags: ['tag'] }` for tag-based revalidation
- `revalidatePath()` and `revalidateTag()` from `next/cache`
- `generateStaticParams()` for static path generation
- Parallel data fetching with `Promise.all()`
- Request memoization — same `fetch()` deduped within a render

---

## 4. Server Actions

- `"use server"` directive — in file or inline in Server Components
- Form actions: `<form action={serverAction}>`
- `useFormState` / `useActionState` (React 19) for progressive enhancement
- `useFormStatus` for pending UI states
- Revalidating after mutations: `revalidatePath()`, `revalidateTag()`
- Redirecting: `redirect()` from `next/navigation`
- Error handling: `try/catch`, returning error state objects
- `next-safe-action` for type-safe server actions with Zod validation

---

## 5. Routing & Navigation

- `useRouter()` from `next/navigation` (App Router)
- `usePathname()`, `useSearchParams()`, `useParams()`
- `<Link>` component — prefetching, `replace`, `scroll`
- Programmatic navigation: `router.push()`, `router.replace()`, `router.back()`
- Middleware: `middleware.ts` at root — runs on Edge, matchers config
- `NextResponse.redirect()`, `NextResponse.rewrite()`, `NextResponse.next()`
- Internationalization (i18n) routing patterns

---

## 6. Pages Router (Legacy / Still Supported)

- `pages/` directory: file-based routing
- `getStaticProps`, `getStaticPaths` for SSG
- `getServerSideProps` for SSR
- `getInitialProps` (avoid — disables automatic static optimization)
- `pages/api/` for API routes
- `_app.tsx`, `_document.tsx` customization
- `next/router` (useRouter) for Pages Router

---

## 7. Styling

- CSS Modules: `styles.module.css` — scoped class names
- Tailwind CSS integration with `tailwind.config.ts`
- `next/font` — self-hosted Google Fonts, zero layout shift
- CSS-in-JS with App Router: only compatible libs (Linaria, Panda CSS, StyleX)
- `clsx` / `cn` utility for conditional classes
- Global styles in `app/globals.css` or `pages/_app.tsx`

---

## 8. Images & Media

- `next/image` — lazy loading, automatic WebP, blur placeholder
- `fill` prop for responsive images inside positioned containers
- `sizes` prop for responsive breakpoints
- Remote image domains in `next.config.js` → `images.remotePatterns`
- `next/video` patterns and self-hosted media
- Static assets in `public/` directory

---

## 9. Authentication

- **NextAuth.js v5 (Auth.js)**: providers, session, callbacks, middleware
- JWT vs database sessions configuration
- `auth()` helper in Server Components and API routes
- Protecting routes with middleware matchers
- Custom credentials provider with Zod validation
- OAuth providers: Google, GitHub, Discord setup

---

## 10. Performance & Optimization

- `next/dynamic` for lazy-loaded Client Components (`ssr: false` option)
- Bundle analyzer: `@next/bundle-analyzer`
- `React.cache()` for server-side request memoization
- Streaming with Suspense — progressive rendering
- `prefetch` on `<Link>` — disabled for authenticated routes
- Static vs dynamic rendering decision tree
- Partial Prerendering (PPR) — experimental Next.js 14+
- `unstable_cache` for caching arbitrary async functions

---

## 11. Configuration (`next.config.js` / `next.config.ts`)

```ts
import type { NextConfig } from 'next'

const config: NextConfig = {
  experimental: {
    ppr: true,           // Partial Prerendering
    serverActions: { allowedOrigins: ['...'] },
  },
  images: {
    remotePatterns: [{ hostname: 'example.com' }],
  },
  redirects: async () => [
    { source: '/old', destination: '/new', permanent: true },
  ],
  headers: async () => [...],
  env: { CUSTOM_VAR: process.env.CUSTOM_VAR },
  turbopack: {},         // Turbopack (replaces Webpack)
}

export default config
```

---

## 12. Deployment

- **Vercel**: zero-config, Edge Functions, Analytics, KV, Blob, Postgres
- **Self-hosted Node.js**: `next build` → `next start`, requires Node 18+
- **Docker**: multi-stage build with `output: 'standalone'` in next.config
- **Static Export**: `output: 'export'` for pure static sites (no SSR)
- Environment variables: `.env.local`, `.env.production`, `NEXT_PUBLIC_` prefix for client
- Edge Runtime: `export const runtime = 'edge'` in route handlers

---

## 13. Testing

- **Jest + React Testing Library** for unit/integration tests
- **Playwright** or **Cypress** for E2E tests
- `jest.config.ts` with `next/jest` transformer
- Mocking `next/navigation` hooks in tests
- `@testing-library/user-event` for user interaction simulation

---

## 14. TypeScript Patterns

```ts
// Page props with params and searchParams
type Props = {
  params: Promise<{ slug: string }>
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}

// Route Handler
import { NextRequest, NextResponse } from 'next/server'
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  return NextResponse.json({ id })
}
```

---

## Core Competency Summary

- Build full-stack apps with App Router, Server Components, and Server Actions
- Implement authentication with NextAuth.js v5
- Optimize for Core Web Vitals and static/dynamic rendering balance
- Deploy on Vercel or self-host with Docker
- Write type-safe Next.js with TypeScript and Zod validation

