Deep AI prompt library for Next.js 15 developers. Covers App Router architecture, Server Components, Server Actions, Route Handlers, authentication with NextAuth v5, Prisma + PostgreSQL, ISR caching, Playwright testing, and Vercel deployment — all production-ready.
Next.js 15 App Router: The AI Prompting Advantage
Next.js 15 with the App Router fundamentally changed how React applications are built — Server Components, Server Actions, streaming, and the fetch cache require a different mental model than Pages Router. The developers shipping the most reliable Next.js applications in 2026 use AI prompts engineered specifically for the App Router paradigm: prompts that specify component rendering strategy, caching behavior, and TypeScript types upfront, rather than discovering them during debugging.
This guide covers every major Next.js production pattern with prompts that produce deploy-ready code. All examples target Next.js 15, TypeScript 5+, and the App Router.
Picking the Right AI Model for Next.js Work
The App Router's Server Components, Server Actions, and edge runtime create patterns that most AI models struggle with — specifically the boundary between server and client. Here's how each model handles Next.js 15 work.
| Model | Best For (Next.js) | Weak Spot | When to Reach For It |
|---|---|---|---|
| Claude Sonnet | App Router architecture, Server vs Client Component decisions, complex data flow analysis | Occasionally suggests Pages Router patterns in mixed codebases | Designing the route hierarchy, reviewing Server Action security, planning ISR vs SSR vs static |
| ChatGPT GPT-5.5 | Component generation from UI descriptions, JSX boilerplate, React hook patterns | Still defaults to useEffect for data fetching instead of Server Components | Generating Client Components from Figma designs, writing form validation with zod + react-hook-form |
| Gemini 3.5 Flash | Vercel ecosystem research, Next.js changelog analysis, framework comparisons | Less reliable on App Router specifics — sometimes mixes App and Pages Router APIs | Researching Turbopack vs Webpack trade-offs, checking what changed in Next.js 15.x |
| Cursor | In-editor generation with awareness of your actual file structure and route groups | Import path hallucinations in deeply nested route groups | Adding a new route handler that follows your existing patterns, refactoring components |
| GitHub Copilot | Completing repetitive route handler boilerplate, Prisma query autocomplete | Suggests deprecated NextRequest APIs; defaults to Pages Router getServerSideProps | Writing the 8th similar API route after it has learned your handler structure |
| Grok | Direct comparison: App Router vs Pages Router, Server Actions vs Route Handlers trade-offs | Less depth on Vercel-specific deployment nuances | Getting an unhedged opinion on whether to use Clerk vs NextAuth v5 for your use case |
| DeepSeek | Boilerplate generation, utility functions, documentation strings | App Router async/await patterns in Server Components — often generates incorrect layouts | Scaffolding repetitive UI components, generating TypeScript type definitions |
Claude handles the App Router's mental model better than any other model right now. The distinction between where async happens (Server Component, Server Action, Route Handler) and why is non-trivial, and Claude reasons about it more accurately. For active coding with your actual codebase open, Cursor is indispensable — it reads your route group structure and suggests file names that actually fit the convention you've established.
One thing every model gets wrong: they default to using use client when it's not needed. Challenge every use client directive an AI adds. If the component fetches data, it should be a Server Component with a Client Component wrapper for interactivity. Most AI-generated Next.js code pushes too much to the client.
1. App Router Architecture Planning
You are a senior Next.js architect who has shipped App Router applications serving 10M+ requests per day.
Design the complete file and folder structure for a Next.js 15 SaaS dashboard application with:
- Authentication: NextAuth v5 with Google + GitHub providers, Prisma adapter, PostgreSQL
- Multi-tenant: each organization gets its own subdomain (acme.app.com)
- Role-based routing: /dashboard (member), /admin (org_admin+), /settings (account owner)
- API layer: Route Handlers for webhooks and mobile clients, Server Actions for all UI mutations
- Background jobs: integration with an external queue (Trigger.dev or similar)
Deliver:
1. Full app/ directory tree including route groups, layout nesting, and (auth) group pattern
2. For each major route: specify Server Component vs Client Component decision with reasoning
3. Data fetching strategy per page: static (revalidate), ISR, or dynamic
4. Middleware.ts plan: which routes are protected, how session is propagated to Server Components
5. Environment variable schema (public vs private, required vs optional)
2. Server Component Data Fetching
Server Components can fetch data directly — no useEffect, no loading states, no client-server waterfalls. Most teams underuse this.
You are a Next.js 15 Server Component expert.
Build a DashboardPage Server Component (app/dashboard/page.tsx) for a project management app:
Data required (all fetched server-side):
- Current user's projects (last 10, sorted by updatedAt)
- Task completion stats for the current organization (aggregate)
- Recent team activity (last 20 events across all projects)
- Current user's assigned tasks due this week
Requirements:
- Parallel data fetching with Promise.all (never sequential await chains)
- React cache() for deduplication of user session lookups across the component tree
- fetch() with cache tags for revalidation: tag('projects'), tag('tasks'), tag('activity')
- Prisma queries in a dedicated data layer (lib/data/dashboard.ts), not inline in the component
- TypeScript types for all data shapes
- Suspense boundaries for each section with meaningful skeleton components
- generateMetadata() function with dynamic page title and og:title
Why it works: Specifying Promise.all instead of sequential awaits prevents the most common Next.js performance mistake — a 4-waterfall chain that adds 800ms to every page load.
3. Server Actions with Validation & Revalidation
You are a Next.js Server Actions expert.
Build a set of Task Server Actions (app/actions/tasks.ts) for a project management app:
Actions required:
- createTask(formData: FormData): create task, revalidate tag('tasks'), redirect to task page
- updateTask(taskId: string, data: Partial<Task>): update with optimistic UI support
- deleteTask(taskId: string): soft delete, revalidate, return success/error
- assignTask(taskId: string, userId: string): update assignee, notify via email queue
Requirements for ALL actions:
- auth() check at the top of every action — throw if unauthenticated
- Zod validation on all inputs (including FormData parsing via zod-form-data)
- Tenant scoping: verify the resource belongs to the current user's organization
- Return type: { success: boolean; data?: T; error?: string; fieldErrors?: Record<string, string[]> }
- Error logging with structured context (action name, user ID, tenant ID, error)
- Never expose internal error messages to the client in production
TypeScript with strict mode. Show usage from a Client Component using useActionState.
4. Route Handler (API Route) — Webhook Processing
You are a senior Next.js API Route Handler architect.
Build a POST /api/webhooks/stripe route handler (app/api/webhooks/stripe/route.ts) for a SaaS billing system:
Requirements:
- Verify Stripe webhook signature using stripe.webhooks.constructEvent (reject on invalid signature — return 400)
- Handle these events: checkout.session.completed, customer.subscription.updated, customer.subscription.deleted, invoice.payment_failed
- Each event handler in a separate function in lib/billing/handlers.ts (not inline in route)
- Idempotency: store processed event IDs in Redis (TTL 24h), skip if already processed
- Error handling: if processing fails, return 500 (Stripe will retry), log with full event context
- Raw body requirement: explain why you cannot use the default body parser and how to handle it in Next.js 15
TypeScript. Include the Stripe client initialization, event type discriminated union, and database update logic for each event type.
5. Next.js Middleware for Auth & Tenant Routing
You are a Next.js middleware expert.
Build a production-grade middleware.ts for a multi-tenant SaaS:
Route protection:
- /dashboard/* — require authentication, redirect to /login if unauthenticated
- /admin/* — require role: org_admin or super_admin, redirect to /dashboard if unauthorized
- /api/* — require valid JWT in Authorization header (except /api/webhooks/*, /api/health)
- /(auth)/* — redirect to /dashboard if already authenticated
Tenant routing:
- Read subdomain from hostname header (acme.yourdomain.com → tenant slug 'acme')
- Validate tenant slug exists in a Redis allowlist (fast lookup, 60s TTL)
- Pass tenantSlug to request headers (x-tenant-slug) for Server Components
- If subdomain is unknown: return 404 with custom tenant-not-found page
Session propagation:
- Decode JWT, attach userId and role to request headers
- Set x-user-id, x-user-role headers for downstream Server Components to read
Include the matcher config and explain which paths are NOT matched and why.
Why it works: Tenant slug validation in Redis, not a database, keeps middleware latency under 5ms. Explaining the matcher exclusions prevents the common mistake of blocking Stripe webhooks or Next.js static assets.
6. NextAuth v5 Configuration
You are a NextAuth v5 authentication expert.
Configure NextAuth v5 (Auth.js) for a multi-tenant SaaS with:
Providers: Google OAuth, GitHub OAuth, and Email (magic link via Resend)
Database: Prisma adapter with PostgreSQL
Custom session fields:
- session.user.id (database user ID, not provider ID)
- session.user.role (fetched from database on every session request)
- session.user.tenantId (organization the user last selected)
- session.user.tenantRole (role within that organization)
Security requirements:
- signIn callback: block disposable email addresses, enforce domain allowlist for enterprise orgs
- jwt callback: fetch fresh role from DB every 15 minutes (not on every request)
- session callback: return only the fields needed by the client (never expose internal IDs to the frontend)
- Account linking: allow same email across providers, merge accounts
Output: auth.ts config, middleware.ts usage, Prisma schema extensions, and client-side usage examples (useSession, auth() in Server Components, auth() in Server Actions).
7. Prisma Schema + Database Layer
You are a Prisma and PostgreSQL expert.
Design a Prisma schema for a multi-tenant SaaS project management app: Tenant, User, TenantMembership, Project, Task, Comment, AuditLog.
Requirements:
- Row-Level Security (RLS) strategy: add tenantId to every table, explain how to enforce with Prisma middleware
- Soft deletes: deletedAt DateTime? on all major entities
- Audit trail: AuditLog model with polymorphic entity reference (entityType, entityId, action, userId, diff JSON, timestamp)
- Indexes: for all foreign keys, common query filters (status, assignedTo, dueDate), and composite unique constraints
- Cascade strategy: Tenant delete cascades to Projects, Projects cascade to Tasks
- Prisma middleware: automatically inject tenantId filter on all queries (context-based tenant isolation)
Output: complete schema.prisma, Prisma middleware file (prisma-tenant.ts), and examples of how queries are automatically scoped to the current tenant.
8. Next.js Performance: Caching Strategy
You are a Next.js performance engineer.
Audit and optimize the caching strategy for these Next.js 15 pages:
1. /dashboard — user-specific data, should be fresh within 60 seconds
2. /blog — public content, can be stale for 24 hours, revalidate on new post published
3. /pricing — marketing page, fully static, update only on deploy
4. /api/search — search results, cache per-query for 5 minutes
5. /profile/[id] — semi-public user profiles, cache for 10 minutes, invalidate on profile update
For each page provide:
- The correct fetch() cache option OR generateStaticParams() + revalidate strategy
- The revalidatePath() or revalidateTag() calls that invalidate this page
- Whether to use React cache() for deduplication within a request
- The expected cache behavior in development vs production
- How to verify the cache is working (response headers to check)
Also explain the difference between the Next.js Data Cache, Router Cache, and Full Route Cache — and which one each page uses.
9. SEO & Metadata API
You are a Next.js SEO specialist.
Implement a complete metadata strategy for a Next.js 15 App Router SaaS:
Root layout (app/layout.tsx):
- metadataBase pointing to production domain
- Default title template: '%s | AppName'
- Default og:image, og:site_name, twitter:card
- Robots, canonical, alternates
Dynamic metadata for these page types:
- Blog posts (app/blog/[slug]/page.tsx): generateMetadata with post title, description, og:image (post hero), article:published_time, author
- User profiles (app/profile/[id]/page.tsx): generateMetadata with user name, bio, og:image (avatar)
- Product pages with variants: canonical pointing to the base product URL (prevent duplicate content)
JSON-LD structured data (server-rendered, not client-side):
- WebSite schema on root layout with SearchAction
- Article schema on blog posts
- SoftwareApplication on the homepage
- BreadcrumbList on all nested pages
Verify all JSON-LD is output in raw HTML (not injected by client JS) — show how to confirm with View Page Source.
10. Playwright E2E Tests for Next.js
You are a Playwright testing expert for Next.js applications.
Write Playwright E2E tests for a Next.js SaaS application covering the critical user journey:
1. New user sign up (Google OAuth mock) → organization creation → onboarding flow
2. Invite team member → member receives email → accepts invite → can access shared project
3. Create project → create tasks → assign to team member → change status through workflow
4. Billing: upgrade to Pro plan (Stripe test mode) → verify feature unlock
For each test:
- Use Playwright fixtures for auth state (save Google OAuth session, reuse across tests)
- Mock external services: Stripe webhooks (local webhook forwarding), email (Resend test mode)
- Assert on both UI state and database state (Prisma queries in test teardown)
- Page Object Model: one page class per major section (DashboardPage, ProjectPage, etc.)
- Visual regression: take screenshots of key states, compare to baseline
- Run in parallel with worker-scoped authentication
Include: playwright.config.ts with multiple browser setup, GitHub Actions integration, and environment variable handling for test vs production Stripe keys.
11. Next.js Error Handling & Observability
You are a Next.js production reliability engineer.
Implement comprehensive error handling and observability for a Next.js 15 App Router application:
Error boundaries:
- Root error.tsx: catch unhandled Server Component errors, show user-friendly message, log to Sentry
- Route-level error.tsx files for Dashboard, API, and Auth sections with context-specific messages
- not-found.tsx: custom 404 with search functionality
- global-error.tsx: last-resort handler for root layout errors
Logging and tracing:
- Pino logger initialized in instrumentation.ts, used in Server Components and Route Handlers
- Request correlation ID: generated in middleware, passed as x-request-id header, included in all log lines
- Sentry integration: capture exceptions with user context (id, tenantId) and Next.js route context
- Performance monitoring: track Largest Contentful Paint, Time to First Byte via Sentry Performance
Rate limiting on Route Handlers:
- Upstash Redis rate limiter middleware factory (returns next() or Response 429 with Retry-After)
- Different limits per endpoint type: auth (5/min), API (100/min), webhooks (unlimited)
Output: all error.tsx files, instrumentation.ts, Sentry config, and rate limiter middleware. TypeScript.
13. Parallel Route + Intercepting Route Pattern
You are a senior Next.js 15 App Router engineer.
Implement a modal photo gallery using Next.js Parallel Routes + Intercepting Routes:
Route structure:
- /photos — main gallery page (Server Component, fetches all photos with pagination)
- /photos/[id] — full photo detail page (direct URL access shows full page)
- @modal slot — intercepts /photos/[id] when navigating from the gallery (shows as modal overlay)
Requirements:
- Intercepting route: (.)photos/[id] — intercept same-level navigation only
- Modal behavior: photo detail appears as overlay on /photos with URL updated to /photos/[id]
- Direct access: navigating directly to /photos/[id] shows the full detail page (no modal)
- Modal close: navigate back (router.back()) OR click backdrop
- State: preserve gallery scroll position when modal opens and closes
- Suspense: loading.tsx for both the full page and modal slot
- TypeScript: Page and Layout component props with the correct slot types
Output: complete file structure with all required Next.js App Router files, including layout.tsx that handles the @modal parallel route slot.
Pro tip: Always add default.tsx files for each parallel route slot — without them, navigating directly to the route throws an unhandled 404 for the slot.
14. Incremental Static Regeneration with On-Demand Revalidation
You are a Next.js performance engineer.
Implement a content-heavy marketing site with Next.js 15 ISR + on-demand revalidation:
Pages to generate: /blog (list), /blog/[slug] (detail), /products/[id]
Data source: headless CMS via REST API (URL from env CMS_API_URL)
Static generation:
- generateStaticParams(): fetch all slugs/IDs at build time, generate first 100 most popular pages
- revalidate = 3600 (1 hour default TTL) at the page level
- notFound: return notFound() if CMS returns 404 (don't throw)
On-demand revalidation:
- POST /api/revalidate — webhook endpoint called by CMS on content publish
- Verify x-webhook-secret header against WEBHOOK_SECRET env var (timing-safe comparison)
- Call revalidatePath('/blog') and revalidateTag('blog-content')
- Support revalidating specific slugs: revalidatePath('/blog/'+slug)
Cache tags: tag every fetch() call for granular invalidation
- fetch(url, { next: { tags: ['blog-content', 'post-'+slug] } })
Output: page components, generateStaticParams, revalidation webhook route, and fetch utilities with proper tagging.
15. Next.js Middleware for A/B Testing
You are a Next.js engineer specializing in edge runtime and experimentation.
Implement A/B testing middleware in Next.js 15 that runs at the edge:
Experiments config (hardcoded, later replaceable with edge config):
- experiment: 'homepage-hero' — variants: ['control', 'variant-a', 'variant-b'], weights: [50, 25, 25]
- experiment: 'pricing-page' — variants: ['monthly-first', 'annual-first'], weights: [50, 50]
Middleware behavior:
- Read experiment assignments from 'ab-experiments' cookie (JSON, signed with HMAC-SHA256 using AB_SECRET env)
- Assign new visitors: weighted random assignment, persist in signed cookie (30-day expiry, SameSite=Lax)
- Rewrite URL: /pricing → /pricing/monthly-first OR /pricing/annual-first (internal only, URL stays /pricing)
- Add response headers: X-Experiment-Homepage, X-Experiment-Pricing for analytics
- Respect Do Not Track: if DNT header is '1', always serve control variant
- Bot detection: skip experiment assignment for known bot user agents, serve control
Output: middleware.ts with matcher config, experiment utility functions, and the signed cookie helpers. Include a client-side hook useExperiment(name) that reads the assignment from cookies for analytics events.
16. Streaming with Suspense and Loading UI
You are a Next.js 15 App Router engineer.
Implement progressive streaming for a dashboard page with multiple independent data sources:
Page: /dashboard
Data sources (each with different latency):
- User stats: fast (~50ms) — total tasks, completed this week, overdue count
- Team activity feed: medium (~300ms) — last 20 actions by team members
- AI insights panel: slow (~2000ms) — LLM-generated weekly summary (streamed from AI API)
- Notifications: fast (~80ms) — unread count and recent notifications
Requirements:
- Each section wrapped in its own Suspense boundary with a skeleton loading.tsx
- Streaming order: fast sections appear immediately, slow sections stream in as ready
- AI insights: use ReadableStream to stream token-by-token from the AI API response
- Error boundaries: each section fails independently — a slow AI response failing doesn't break the stats section
- No client-side waterfalls: all fetches initiate in parallel (Promise.all or fetch in parallel at the Server Component level)
Output: dashboard page component, all async Server Components for each section, skeleton components, and the AI streaming Server Action.
17. Database Migrations with Prisma
You are a Next.js + Prisma backend engineer.
Set up a safe Prisma migration workflow for a Next.js 15 production app on Vercel + PlanetScale (or Neon):
Current schema state: [PASTE CURRENT schema.prisma]
Required changes: [DESCRIBE THE CHANGE — e.g., "Add a UserProfile model related to User 1:1, add stripeCustomerId to User, add index on Post.authorId + Post.publishedAt"]
Deliver:
1. Updated schema.prisma with the changes
2. The migration SQL — generate with prisma migrate dev --create-only and paste it
3. Review the migration for: adding NOT NULL columns to tables with existing rows (must have DEFAULT or do in 3 steps), dropping columns (verify no code references them), index additions (additive, safe)
4. A deploy checklist: when to run migrate deploy (before or after code deploy?), how to verify the migration applied in production
5. A rollback plan: what to run if the migration fails halfway through on a 5M-row table
Context: the app gets 500 req/s — migrations must not lock tables for more than 2 seconds.
18. Multi-Tenant Architecture in Next.js
You are a senior Next.js architect specializing in SaaS multi-tenancy.
Design a subdomain-based multi-tenant Next.js 15 App Router application:
Tenant routing strategy: subdomain (acme.app.com, globex.app.com) + path fallback for localhost (app.localhost:3000/tenant/acme)
Middleware requirements:
- Extract tenant from subdomain OR x-tenant-id header (for API clients)
- Look up tenant in edge-compatible store (Vercel KV or Upstash Redis) — cache 60s TTL
- If tenant not found: return 404 page (not redirect)
- Attach tenantId to request headers for downstream Server Components and Route Handlers
- Rewrite: internal path stays the same, tenant context flows through headers
Data isolation: Prisma with tenantId on every model, Row-Level Security pattern via Prisma middleware that automatically appends .where({ tenantId }) on every query
Per-tenant theming: tenant-specific CSS variables loaded in layout.tsx based on tenant config (primary color, logo URL, font) — no Flash of Unstyled Content
Output: middleware.ts, tenant resolution utility, Prisma tenant middleware, and the layout.tsx theming pattern.
End-to-End Workflow: Authenticated CRUD Feature
This is how you chain Next.js prompts to ship a complete authenticated data feature from schema to UI in one session.
- Schema (Prompt 7 variant): "Design the Prisma schema for a Team model — many-to-many with User, with a TeamMember join table that has a role field (admin/member). Include createdAt, updatedAt, tenantId. Generate the migration SQL."
- Server Action (Prompt 3 variant): "Create a createTeam Server Action in app/teams/actions.ts: validate with Zod (name required, min 3 chars; description optional max 500), create the Team and TeamMember (role: admin for creator) in a Prisma transaction, revalidate /teams, return typed result { success, data?, error? }."
- Server Component (Prompt 2 variant): "Create the /teams page as an async Server Component: fetch teams where the current user is a member using NextAuth session, display as a grid with team name, member count, and role badge. Use Suspense with a skeleton."
- Route Handler for API access (Prompt 4 variant): "Create GET /api/teams and POST /api/teams Route Handlers for mobile app access — same business logic as the Server Action, but with Bearer token auth and JSON responses."
- E2E Tests (Prompt 10 variant): "Write Playwright E2E tests for the teams feature: create team, invite member, verify member sees team, verify non-member gets 403."
Between each step: run npx tsc --noEmit and fix errors before moving forward. The type errors from step to step are your integration tests before you write integration tests.
Where AI Goes Wrong in Next.js
- Pages Router patterns in App Router files. AI generates
getServerSideProps,getStaticProps, anduseRouterfrom next/router (not next/navigation) inside App Router components. Always specify "Next.js 15 App Router" explicitly, never just "Next.js." - Unnecessary
use clientdirectives. AI defaults to making almost everything a Client Component. Challenge everyuse client. If the component only renders data without interactivity, it should be a Server Component. - Incorrect async Server Component patterns. AI sometimes generates
asyncClient Components (impossible) orawaitinside non-async Server Components. The distinction matters for the React tree and Suspense boundaries. - Missing
cache: 'no-store'on sensitive fetches. Next.js 15 caches fetch() by default. AI-generated data fetching often misses the cache control options — user-specific data gets cached across users. Specify "this is user-specific data, do not cache" in every prompt. - Server Actions without CSRF consideration. Server Actions have CSRF protection built in for same-origin calls, but AI-generated actions sometimes add redundant manual CSRF tokens or, worse, strip the origin check for "simplicity."
- Stale next/headers and next/cookies usage. The APIs changed in Next.js 15 — headers() and cookies() are now async in some contexts. AI trained before the change generates synchronous calls that throw at runtime.
12. Good vs Bad Next.js Prompts
| Task | ❌ Bad Prompt | ✅ Good Prompt |
|---|---|---|
| Data fetching | "How do I fetch data in Next.js?" | "Write a Server Component that fetches a user's projects with Promise.all (parallel), uses React cache() for session deduplication, applies fetch() with cache tag 'projects' for ISR revalidation, and passes data to Client Components via props (not context). TypeScript, Next.js 15 App Router." |
| Server Actions | "Create a form action" | "Write a Server Action createTask() for Next.js 15: auth() check, Zod validation of FormData, Prisma insert scoped to user's tenantId, revalidateTag('tasks'), return { success, data?, error?, fieldErrors? }. Show useActionState usage in the form Client Component." |
| Authentication | "Add login to my Next.js app" | "Configure NextAuth v5 with Google provider + Prisma PostgreSQL adapter. Add custom jwt callback to embed userId, role, and tenantId. Protect /dashboard/* in middleware.ts using auth(). Show how to read session in a Server Component without a client component." |
| Caching | "Make my app faster" | "My /dashboard page re-fetches all data on every navigation. Implement: React cache() for user session dedup, fetch() with revalidate:60 for project list, revalidatePath('/dashboard') called from Server Actions on mutation. Explain which of the three Next.js cache layers each change affects." |
Before You Prompt: Next.js Context Setup
The single biggest reason AI generates outdated or wrong Next.js code is missing project context. Before starting any session with ChatGPT, Claude, or Cursor, paste this setup block as your first message — it prevents the majority of version drift and Pages Router contamination:
Context for all prompts in this session:
- Framework: Next.js 15.2, App Router (NOT Pages Router)
- Language: TypeScript 5.4, strict mode enabled
- Styling: Tailwind CSS v4
- Database/ORM: Prisma 5 + PostgreSQL (swap for your actual ORM)
- Auth: NextAuth v5 (Auth.js) — use auth(), NOT getServerSession()
- State management: Zustand 5 + TanStack Query v5
- Deployment: Vercel (Edge Runtime available for Middleware)
- Node.js: 20.x LTS
Never generate:
- Pages Router patterns (getServerSideProps, getStaticProps, pages/ directory)
- useEffect for data fetching (use Server Components instead)
- Class components
- CommonJS require() (always ESM import)
Adapt this block to your actual stack. The "Never generate" list is as important as the positive constraints — it gives the model explicit permission to flag legacy patterns before they reach your codebase. Teams that version-control their AI context file in a CONTEXT.md ship more consistent, reviewable code than teams that re-describe the stack in every session. Update the block any time you upgrade a major dependency.
3 Common Mistakes When Prompting AI for Next.js
Mistake 1: Not specifying App Router vs Pages Router
Asking "write a data fetching component in Next.js" without specifying the router version produces inconsistent results — one session returns a Server Component, the next returns getServerSideProps. Both are valid Next.js, but they are architecturally incompatible inside the same app. Always say "Next.js 15 App Router" in every prompt. Even with a context block, re-state it on any prompt generating page-level components or layouts.
Mistake 2: Asking for "authentication" without specifying NextAuth v4 vs v5
NextAuth v5 (Auth.js) has a fundamentally different API from v4. The auth() function, Server Component integration, and middleware.ts pattern all changed. AI defaults to v4 patterns — especially getServerSession(authOptions) — which won't work with the v5 export pattern. Specify "NextAuth v5 / Auth.js — use auth() exported from auth.ts, not getServerSession()." Four extra words prevent an hour of debugging.
Mistake 3: Asking for caching without naming the cache layer
Next.js has three independent cache systems: the Data Cache (fetch with tags), the Router Cache (client navigation), and the Full Route Cache (static renders). "Cache this page" is ambiguous — AI picks one without explaining the choice. Ask: "What cache layer applies to this component, and what call correctly invalidates it?" The answer determines whether you call revalidatePath(), revalidateTag(), or router.refresh() — getting this wrong means stale user data in production.
Further Reading
To get more out of AI-assisted Next.js development, these resources go deeper on strategy and tooling:
- How engineering teams use AI for development — pair programming workflows, code review strategies, and how to integrate AI into a Next.js sprint without slowing your team down
- How to write the perfect AI prompt — the principles that make every prompt in this guide work, applicable to any framework or task type
- AI Coding Prompt Library — 50+ copy-ready prompts for debugging, refactoring, test generation, and architecture decisions across Next.js and other stacks
Generate a custom Next.js prompt for your specific use case → Try PromptPrepare free
Help & Answers
Frequently Asked Questions
Found this helpful?
Save it to your library or share with your team.
Keep Reading