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.
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.
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." |
Generate a custom Next.js prompt for your specific use case → Try PromptPrepare free
Found this helpful? Share it.