Skip to main content

Scenario: Next.js Full-Stack with AEEF Standards

This walkthrough shows how to apply AEEF production standards together on a real Next.js project. Unlike individual tutorials that cover one tool or standard, this scenario follows an entire feature from idea to production, showing how the standards reinforce each other.

Time required: 60-90 minutes (reading + doing) Prerequisites: Familiarity with Next.js 14+, TypeScript, and basic AEEF concepts from the Startup Quick-Start.

Composite Scenario

This is a realistic composite scenario showing how standards apply together. Adapt the specifics to your stack — the governance workflow is universal.


The Project

A SaaS project management tool built with:

  • Frontend: Next.js 14 (App Router) with TypeScript
  • Backend: Next.js API Routes + Server Actions
  • Database: PostgreSQL via Prisma ORM
  • Auth: NextAuth.js with JWT
  • Testing: Vitest + React Testing Library + Playwright
  • CI: GitHub Actions

The team has 6 engineers and has completed the Starter Config Files and CI/CD Pipeline Starter tutorials.

The Feature

User story: As a project owner, I can invite team members by email so they can collaborate on my projects.

This feature touches:

  • Database schema (new invitation model)
  • API endpoint (create invitation)
  • Server Action (accept invitation)
  • UI component (invitation form + pending list)
  • Email notification (send invite)
  • Authorization (only project owners can invite)

Phase 1: Prompt Engineering (PRD-STD-001)

Step 1.1: Structured Prompt for Data Model

Using the TypeScript Secure Endpoint template (prompt-library/by-language/typescript/secure-endpoint.md) adapted for Prisma:

You are a senior TypeScript engineer working in a Next.js 14 codebase.

**Context:**
- Next.js 14 App Router with TypeScript strict mode
- Database: PostgreSQL via Prisma ORM
- Auth: NextAuth.js with JWT sessions
- Validation: Zod

**Task:** Create the data model and API for project invitations.

**Requirements:**
1. Invitation model: projectId, email, role (admin/member/viewer),
status (pending/accepted/expired), invitedBy, token, expiresAt
2. Unique constraint on (projectId, email) for pending invitations
3. Token must be cryptographically random (not predictable)
4. Invitations expire after 7 days

**Constraints:**
- Use Zod schemas for all input validation
- Use parameterized queries only (Prisma handles this)
- Generate a secure token using crypto.randomUUID(), not Math.random()
- Return proper HTTP status codes (201 created, 409 already invited)
- Check that the requester is the project owner before allowing invite

Step 1.2: Record the Prompt Reference

In your PR description (per Starter Config template):

AI-Usage: claude
AI-Prompt-Ref: by-language/typescript/secure-endpoint (adapted for Prisma)
AI-Confidence: high — model generation, medium — auth logic

Phase 2: Human-in-the-Loop Review (PRD-STD-002)

Step 2.1: Review AI Output Against Checklist

Using the TypeScript PR Risk Review prompt (prompt-library/by-language/typescript/pr-risk-review.md), have the AI review its own output (or a second AI instance review):

Critical items for this feature:

CheckWhat to VerifyStatus
Auth bypassDoes the API check project ownership BEFORE creating the invitation?
Token securityIs the token generated with crypto.randomUUID() or crypto.randomBytes(), not Math.random()?
SQL injectionPrisma uses parameterized queries by default — verify no raw SQL with string interpolation
Input validationIs the email validated server-side (not just client-side)? Is the role restricted to the enum?
Race conditionWhat happens if two people invite the same email simultaneously? (unique constraint handles this)
ExpirationIs the 7-day expiry checked when accepting, not just when listing?

Step 2.2: Verify Against Common AI Pitfalls

From the TypeScript anti-patterns table (prompt-library/by-language/typescript.md):

  • No any types in the invitation flow
  • No as type assertions hiding type mismatches
  • Error handling returns structured responses, not raw exceptions
  • Date comparisons use proper timezone handling

Phase 3: Testing (PRD-STD-003)

Step 3.1: Generate Test Matrix

Use the TypeScript Risk-Based Test Matrix prompt (prompt-library/by-language/typescript/test-matrix.md):

Feature: Project invitation system
Changes: Prisma model, API route, Server Action, React component

Generate a risk-based test matrix covering:
1. Unit tests for invitation creation logic and Zod validation
2. Integration tests for the API endpoint (authenticated, unauthorized, duplicate)
3. Component tests for the invitation form (happy path, validation errors)
4. E2E test for the full invite → accept flow

Expected test coverage:

Test TypeCountWhat It Covers
Unit (Vitest)8-12Zod schema validation, token generation, expiry logic
API integration6-8Create/accept/list endpoints with auth states
Component (RTL)4-6Form submission, error display, loading states
E2E (Playwright)1-2Full flow: invite → email → accept → access

Step 3.2: Verify AI-Generated Tests

Common issues with AI-generated tests (from React Testing Strategy — prompt-library/by-framework/react/testing-strategy.md):

  • Tests use userEvent not fireEvent
  • Tests query by accessible role/label, not data-testid
  • Tests assert on user-visible outcomes, not component state
  • API tests check both success and error responses
  • No time.sleep or arbitrary delays — use waitFor

Phase 4: Security Scanning (PRD-STD-004)

Step 4.1: Automated CI Checks

Your CI pipeline (from the CI/CD Pipeline Starter) should catch:

# These run automatically on every PR
- Semgrep: XSS, SQL injection, insecure randomness
- Trivy: Dependency vulnerabilities
- npm audit: Known CVEs in dependencies
- ESLint security plugin: React-specific security rules

Step 4.2: Manual Security Review

Use the React Security Review prompt (prompt-library/by-framework/react/security-review.md) to check:

  • Invitation token not exposed in client-side JavaScript
  • Email addresses not leaked in client-side state to unauthorized users
  • Accept-invitation page validates token server-side before rendering
  • No open redirect after accepting invitation

Phase 5: Quality Gates (PRD-STD-007)

Step 5.1: PR Checklist

Before merging, verify all quality gates pass:

GateToolPass Criteria
Type safetytsc --noEmitZero errors
LintESLint + BiomeZero errors (warnings reviewed)
Unit testsVitest100% passing, new code covered
Integration testsVitestAPI tests passing
Security scanSemgrepZero high/critical findings
Dependency auditnpm auditZero high/critical CVEs
Buildnext buildSuccessful with no warnings

Step 5.2: PR Metadata

Your PR description should include:

## Changes
- Add invitation model with Prisma migration
- Add POST /api/projects/[id]/invitations endpoint
- Add invitation accept Server Action
- Add InvitationForm and PendingInvitationsList components

## AI Disclosure
- AI-Usage: claude
- AI-Prompt-Ref: by-language/typescript/secure-endpoint, by-framework/react/component-implementation
- AI-Review: Used by-language/typescript/pr-risk-review for self-review
- Human-Review: Auth logic manually verified, token generation manually verified

## Testing
- 11 unit tests (Zod validation, token logic, expiry)
- 7 API integration tests (CRUD + auth boundary)
- 5 component tests (form + list)
- 1 E2E test (full invite flow)

Phase 6: Dependency Compliance (PRD-STD-008)

If the feature added new dependencies (e.g., an email library), use the TypeScript Dependency Risk Check (prompt-library/by-language/typescript/dependency-check.md):

Review this dependency addition:
- nodemailer@6.9.x (email sending)
- @types/nodemailer (type definitions)

Check: license, CVEs, bundle size, maintenance status, alternatives.

Phase 7: Documentation (PRD-STD-005)

Use the TypeScript Change Runbook (prompt-library/by-language/typescript/change-runbook.md) to generate:

  1. Migration notes: Prisma migration must run before deployment
  2. Environment variables: SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, INVITE_FROM_EMAIL
  3. Rollback procedure: Revert migration, remove env vars, redeploy previous version
  4. Monitoring: Alert on invitation creation failure rate > 5%

Summary: Standards Applied

StandardHow It Was AppliedEvidence
PRD-STD-001 (Prompt Engineering)Structured prompts from language templatesPR description AI-Prompt-Ref
PRD-STD-002 (Code Review)AI + human review with checklistReview comments on PR
PRD-STD-003 (Testing)Risk-based test matrix, 24+ testsCI test results
PRD-STD-004 (Security)Automated scans + manual security reviewCI scan output
PRD-STD-005 (Documentation)Generated runbook from templatePR description + runbook
PRD-STD-007 (Quality Gates)All gates passing before mergeCI status checks
PRD-STD-008 (Dependencies)Dependency risk check for new packagesPR comment with assessment

What This Demonstrates

  1. Standards compose — each standard covers a different risk dimension; together they provide layered defense
  2. Prompts are reusable — language and framework templates saved time vs writing prompts from scratch
  3. AI reviews AI — using review prompts on AI-generated code catches patterns humans might miss
  4. Governance is lightweight — the total overhead for a single feature was ~20 minutes of governance work on top of development
  5. Evidence is automatic — CI output, PR metadata, and review comments create an audit trail without extra effort

Apply This Pattern in Your Repo

Use this scenario as a reference pattern, then choose an implementation path:

Next Steps