web-nextjs
Next.js 15: App Router, server actions, ISR/SSG/SSR, middleware, turbopack, Vercel deployment
What this skill does
# web-nextjs
## Purpose
This skill provides expertise in building and deploying web applications with Next.js 15, focusing on modern features like App Router, server actions, and optimized rendering strategies.
## When to Use
Use this skill for projects requiring fast, SEO-friendly React apps with server-side logic; ideal for e-commerce sites needing SSR, blogs with SSG, or dynamic apps with ISR; avoid for simple static sites where plain React suffices.
## Key Capabilities
- App Router: Enables file-based routing in the /app directory for better organization; example: create a route with app/about/page.jsx.
- Server Actions: Perform mutations on the server without API routes; define as async functions in forms, e.g., 'use server' directive in components.
- ISR/SSG/SSR: Configure ISR via revalidatePath() in server actions; SSG with getStaticProps; SSR with getServerSideProps for dynamic data fetching.
- Middleware: Write edge functions in middleware.js to handle authentication or redirects, e.g., checking user sessions before page loads.
- Turbopack: Speeds up development with incremental bundling; enable via next.config.js with experimental: { turbopack: true }.
- Vercel Deployment: Deploy apps with zero-config via Vercel CLI; supports automatic ISR invalidation through webhooks.
## Usage Patterns
To build a Next.js app, start by creating a project: run `npx create-next-app@latest my-app --typescript` and navigate to the /app directory for routing. For server actions, import and use them in forms: e.g., in a component, add `async function addItem() { 'use server'; await db.insert(item); }`. Implement SSR by exporting getServerSideProps from a page: export async function getServerSideProps() { const data = await fetchData(); return { props: { data } }; }. For ISR, use revalidate in actions: e.g., revalidatePath('/posts') after updating content. Example 1: Build a blog with SSG—create app/posts/[id]/page.jsx with getStaticProps to fetch posts, then run `next build` for static output. Example 2: Add authentication middleware—create middleware.js with export function middleware(request) { if (!request.cookies.token) return NextResponse.redirect('/login'); } and test with `next dev`.
## Common Commands/API
- Create project: `npx create-next-app@latest my-app --app` to use App Router; add --typescript for TypeScript support.
- Development server: `next dev --port 3001` to run on a specific port with hot reloading.
- Build and deploy: `next build` for production build, then `vercel --prod` for deployment; use Vercel API endpoint like POST https://api.vercel.com/v13/now/deployments?teamId=$VERCEL_TEAM_ID with JSON body { "name": "my-app" }.
- API routes: Define in app/api/route.js, e.g., export async function GET(request) { const data = await fetch('https://api.example.com'); return Response.json(data); }.
- Config formats: Edit next.config.js for custom settings, e.g., module.exports = { images: { domains: ['example.com'] }, experimental: { appDir: true } }; use .env.local for env vars like NEXT_PUBLIC_API_URL="https://api.example.com".
- Turbopack commands: Enable in next.config.js and run `next dev` for faster iterations.
## Integration Notes
Integrate databases like PostgreSQL via Prisma: install @prisma/client, run `npx prisma migrate dev`, and use in server actions with env var $DATABASE_URL for connection strings. For auth, use NextAuth.js: install next-auth, configure in [...nextauth].js, and set $NEXTAUTH_SECRET in .env; example: import NextAuth from 'next-auth'; export default NextAuth({ providers: [] }). Link with Vercel for CI/CD by adding vercel.json with { "routes": [{ "src": "/api/(.*)", "dest": "/api/$1" }] }. If API keys are needed, store as env vars like $STRIKE_API_KEY and access via process.env.STRIKE_API_KEY in components.
## Error Handling
Handle 404s by creating app/404.js with a custom page: export default function NotFound() { return <h1>404 - Page Not Found</h1>; }. Use error boundaries in components: wrap with <ErrorBoundary fallback={<div>Error occurred</div>}>; in App Router, add error.js files per route. For build errors, check next.config.js for misconfigurations; common fix: ensure all imports are correct in server components. Debug SSR issues by running `next build --debug` and inspecting logs; for API errors, use try/catch in actions, e.g., try { await fetchData(); } catch (error) { console.error(error.message); return NextResponse.json({ error: 'Fetch failed' }, { status: 500 }); }.
## Graph Relationships
- Related to cluster: web-dev (e.g., shares resources with other web-dev skills like frontend-react).
- Connected via tags: nextjs (links to advanced-react skills), react (integrates with state-management tools), fullstack (overlaps with backend-node skills), web (connects to deployment-vercel skills).
Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.