This document provides a set of templates and guidelines for architecting modern, scalable web and mobile applications. It is structured using a spec-driven development methodology, inspired by agentic IDEs like Amazon Kiro, to ensure clarity, consistency, and efficient collaboration between human developers and AI assistants.1 The following sections serve as adaptable blueprints for key architectural documents.
These three documents—product.md, tech.md, and structure.md—establish the foundational context for a project.3 They are living documents intended to guide all development efforts, providing project-specific intelligence that enables AI agents to generate consistent and architecturally sound contributions.5
Purpose: This document defines the "what" and "why" of the application. It is the strategic constitution of the project, ensuring all features align with user needs and business goals. It should be the first point of reference for any developer, human or AI, when starting a new feature.1
1. Product Vision & Mission
- Vision Statement: A concise, aspirational statement describing the long-term goal of the product.
- Example: "To become the leading platform for collaborative, real-time project management for remote teams."
- Mission Statement: A clear, actionable statement that outlines the product's core purpose and how it achieves its vision.
- Example: "Our mission is to empower remote teams by providing an intuitive and powerful suite of tools that streamline communication, task tracking, and resource allocation."
2. Target User Personas
- Describe the primary user archetypes. This helps focus development on solving real-world problems for specific groups.
- Persona 1:
- Description:
- Needs & Pain Points:
- Persona 2:
- Description: [...]
- Needs & Pain Points: [...]
- Persona 1:
3. Core Features & User Journeys
- List the essential features that define the core user experience.
- Example Feature: User Authentication
- User Story: As a new user, I want to sign up with my email and password so that I can securely access the platform.
- Example Feature: Project Creation
- User Story: As a project manager, I want to create a new project and invite team members so that we can begin collaborating.
- Example Feature: User Authentication
4. Key Success Metrics
- Define the quantifiable metrics that will be used to measure the product's success.
- Example Metric: User Engagement
- Measurement: Daily Active Users (DAU) / Monthly Active Users (MAU) ratio.
- Target: Achieve a DAU/MAU ratio of >25%.
- Example Metric: User Retention
- Measurement: Week 1 user retention rate.
- Target: Achieve a retention rate of >30%.
- Example Metric: User Engagement
Purpose: This document codifies the project's technology stack and the core principles that guide all technical decisions. It serves as a rulebook to ensure consistency, prevent architectural drift, and provide a clear rationale for why certain tools are chosen over others.1
1. Architectural Axioms
These principles should underpin all technology choices, ensuring a robust and maintainable codebase. They are derived from the successful philosophy of the T3 Stack.6
- Axiom 1: Solve Problems, Don't Add "Everything". Every library or technology must solve a specific, existing problem. Avoid adding dependencies for their own sake. This keeps the codebase lean and focused.
- Axiom 2: Bleed Responsibly. Embrace modern, cutting-edge technology for its benefits, but do so with pragmatism. Use newer, riskier technologies in less critical parts of the stack (e.g., an easily replaceable API layer like tRPC) while relying on battle-hardened solutions for core components (e.g., a SQL database).
- Axiom 3: Typesafety Isn't Optional. End-to-end typesafety is a non-negotiable feature. It enhances developer productivity, enables powerful tooling, and reduces bugs. Any decision that compromises typesafety should be heavily scrutinized.
2. Technology Stack Recommendations
This section outlines best-in-class, open-source technologies for each layer of a modern application. Each recommendation is scalable and compatible with modern frameworks like Next.js 15 and React 19.
Layer | Primary Recommendation | Rationale & Key Features | Strong Alternatives | |
---|---|---|---|---|
Monorepo Tooling | NX | Best for complex, polyglot projects. Offers a rich plugin ecosystem (including Python), advanced dependency graphing, and robust caching.9 | Turborepo : A lightweight, high-performance build tool ideal for pure JavaScript/TypeScript projects. Excellent integration with Vercel. | |
Web Framework | Next.js | The industry standard for building full-stack React applications. Provides optimized performance with SSR, SSG, and React Server Components. | Remix, Astro | |
Universal Framework | Expo | Build for Web, iOS, and Android from a single TypeScript codebase. Features a powerful CLI, Over-the-Air (OTA) updates, and a rich ecosystem of native modules | Tamagui (for performance-focused universal UI) | |
API Layer | tRPC | Enables end-to-end typesafe APIs with zero code generation. Unbeatable developer experience in a full-stack TypeScript monorepo. | GraphQL, REST (with OpenAPI) | |
Database | PostgreSQL | A powerful, open-source relational database known for its reliability, robustness, and performance at scale. | MySQL, SQLite (for smaller projects) | |
Database ORM | Drizzle ORM | A lightweight, performant, and type-safe SQL query builder. Offers a familiar, SQL-like syntax and excellent developer experience. | Prisma: A popular, full-featured ORM with a powerful query engine and schema migration tools. | |
Authentication | better-auth | A comprehensive, framework-agnostic authentication framework for TypeScript. Self-hostable, highly extensible, and avoids vendor lock-in. | Supabase Auth (Excellent for rapid MVP development), | Clerk, Auth.js |
AI/ML Services | FastAPI (Python) | A high-performance Python web framework ideal for building AI/ML APIs. Offers automatic documentation and leverages Python's type hints. | Flask, Django Ninja | |
Headless CMS | PayloadCMS | A developer-first, open-source headless CMS built with TypeScript and React. Offers code-based configuration, deep Next.js integration, and a highly extensible admin panel | Strapi (GUI-first, user-friendly), | Directus (Open data platform, introspects existing SQL DBs) |
Client Data Fetching | TanStack Query 24 | The de-facto standard for managing server state in React. Provides caching, background refetching, and optimistic updates for a fast UI | SWR, Apollo Client (for GraphQL) | |
UI Data Grids | TanStack Table | A headless UI library for building powerful and fully customizable data tables and grids. Framework-agnostic and highly performant. | AG Grid | |
E2E Testing | Playwright | A modern, reliable end-to-end testing framework. Offers true cross-browser support (Chromium, Firefox, WebKit), auto-waits, and free parallel execution. | Cypress 28: Known for its excellent developer experience and interactive test runner, though with more limited browser support | |
Component Testing | Storybook | An essential tool for developing UI components in isolation. Serves as a component workshop, testing environment, and living documentation | Ladle |
Purpose: This document provides a definitive map of the project's directory structure and code conventions. It enables any developer to quickly navigate the codebase, understand the purpose of each module, and correctly place new files and logic.1
1. Monorepo Philosophy
This project utilizes a monorepo to foster code sharing, ensure consistency, and streamline dependency management across multiple applications and services. All shared logic, types, and UI components are located in dedicated packages, which are consumed by the applications.
2. Directory Map
The following structure provides a scalable and organized layout suitable for a multi-application project.
/
├── apps/
│ ├── web/ # Primary Next.js application (e.g., marketing site, admin dashboard)
│ └── mobile/ # Universal Expo application (iOS, Android, and web app)
│
├── packages/ (or libs/ in NX)
│ ├── api/ # Shared tRPC router, procedures, and API types
│ ├── auth/ # Authentication configuration and hooks (swappable)
│ ├── db/ # Database schema (Drizzle/Prisma), client, and migrations
│ ├── ui/ # Shared, reusable React component library (e.g., Button, Input)
│ └── utils/ # Shared utility functions and constants
│
├── services/
│ └── ai-service/ # Standalone Python/FastAPI service for AI/ML features
│
├── toolchain/
│ ├── eslint-config/ # Shared ESLint configuration
│ └── tsconfig/ # Shared TypeScript configurations
│
└──... (root configuration files: package.json, nx.json, etc.)
3. Module Responsibilities
- apps/: Contains deployable applications. Each folder is a standalone project that consumes shared logic from the packages/ directory.
- packages/: Contains shared code that is not independently deployable. This is the core of the monorepo's code-sharing strategy.
- ui: Should only contain presentation components.
- api: Defines the backend API contract.
- db: The single source of truth for the data model.
- services/: Contains independently deployable backend services, often in different languages (e.g., Python), that support the main applications.
For each new feature, a set of specification documents should be created before writing code. This methodology translates ideas into formal requirements, technical blueprints, and actionable tasks, providing essential context for AI-driven development.1
Purpose: This document captures what a feature must do in an unambiguous and testable format. It serves as the contract between the product vision and engineering execution.
To achieve maximum clarity for both humans and AI, functional requirements should be written using the EARS (Easy Approach to Requirements Syntax). EARS provides simple, structured templates that prevent ambiguity.
EARS Requirement Patterns:
- Ubiquitous: A system-wide requirement that is always active.
- Syntax: The <system name> shall <system response>.
- Example: The system shall encrypt all user passwords.
- Event-Driven: A system response to a discrete trigger.
- Syntax: When <trigger>, the <system name> shall <system response>.
- Example: When a user clicks the "Save" button, the system shall persist the form data to the database.
- State-Driven: A continuous system behavior while a certain condition is true.
- Syntax: While <precondition>, the <system name> shall <system response>.
- Example: While a user is in "offline mode", the system shall disable the "Sync" button.
- Optional Feature: Behavior for a feature that may not be present in all configurations.
- Syntax: Where <feature is included>, the <system name> shall <system response>.
- Example: Where the "Advanced Reporting" module is enabled, the system shall display the "Export to PDF" option.
- Undesirable Behavior (Error Handling): The system's response to an unwanted situation.32
- Syntax: If <undesirable event>, then the <system name> shall <system response>.
- Example: If a user enters an invalid email format, then the system shall display an error message.
Purpose: This document translates the "what" from requirements.md into a concrete "how," outlining the necessary architectural components, data models, and interfaces for implementation.3
1. Architecture & Data Flow
- A high-level diagram illustrating the interaction between components (e.g., Frontend -> API -> Database). Use Mermaid.js syntax for version-controllable diagrams.
Code snippet
sequenceDiagram
participant User
participant Frontend
participant API
participant Database
User->>Frontend: Clicks "Create Post"
Frontend->>API: tRPC Mutation: posts.create({title, content})
API->>Database: INSERT INTO posts (...)
Database-->>API: Return new post record
API-->>Frontend: Return new post data
Frontend->>User: Display "Post created successfully"
2. Data Model Changes
- Define any new or modified database tables using Drizzle schema syntax.
TypeScript
// In packages/db/schema.ts
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: varchar('title', { length: 256 }).notNull(),
content: text('content'),
authorId: integer('author_id').references(() => users.id),
createdAt: timestamp('created_at').defaultNow().notNull(),
});
3. API Endpoint Specification
- Define the new tRPC procedures required for the feature.
-
Procedure: posts.create
-
Type: mutation
-
Access: protectedProcedure (requires authentication)
-
Input (Zod Schema):
TypeScript
z.object({
title: z.string().min(5),
content: z.string().optional(),
}) -
Output: The newly created post object.
-
4. UI Component Breakdown
- List new UI components to be created in packages/ui.
- Component: PostCard
- Props: (post: Post)
- Description: A card component to display a post's title, author, and creation date.
Purpose: This document breaks down the design into a granular, step-by-step checklist. It is structured to be executed sequentially by either a human developer or an AI coding assistant.16
1. Task Checklist
- A dependency-ordered list of discrete coding tasks. Each task should be small and verifiable.
- MODIFY FILE packages/db/schema.ts: Add the new posts table schema as defined in design.md.
- RUN COMMAND: pnpm db:generate to create the SQL migration file.
- CREATE FILE packages/api/src/router/post.ts: Implement a new postRouter.
- MODIFY FILE packages/api/src/router/post.ts: Add the posts.create mutation procedure as specified in design.md.
- CREATE FILE packages/ui/src/PostCard.tsx: Implement the PostCard presentational component.
- CREATE FILE apps/web/src/app/posts/CreatePostForm.tsx: Build the form UI for creating a new post, using the posts.create tRPC mutation.
- GENERATE TEST: Write a Vitest unit test for the posts.create mutation, covering success and validation error cases.
2. AI Liberty Clause
- This directive defines the scope of the AI's autonomy, balancing automation with control.
- Definition: "The AI has liberty in the stylistic implementation of UI components (e.g., specific TailwindCSS classes) and in refactoring non-critical helper functions for clarity. All changes must adhere to the project's ESLint rules and pass all tests. The AI does not have liberty to alter core architectural patterns, modify database schemas beyond explicit instructions, or add new third-party dependencies without being directed to do so in a tasks.md file."
Works cited
- Kiro Agentic AI IDE: Beyond a Coding Assistant - Full Stack Software Development with Spec Driven AI | AWS re:Post, accessed July 24, 2025, https://repost.aws/articles/AROjWKtr5RTjy6T2HbFJD_Mw/%F0%9F%91%BB-kiro-agentic-ai-ide-beyond-a-coding-assistant-full-stack-software-development-with-spec-driven-ai
- T3 Open Source - GitHub, accessed July 24, 2025, https://github.com/t3-oss
- t3-oss/create-t3-turbo: Clean and simple starter repo using ... - GitHub, accessed July 24, 2025, https://github.com/t3-oss/create-t3-turbo
- t3-oss/create-t3-app: The best way to start a full-stack, typesafe Next.js app - GitHub, accessed July 24, 2025, https://github.com/t3-oss/create-t3-app
- create-t3-app/turbo.json at main - GitHub, accessed July 24, 2025, https://github.com/t3-oss/create-t3-app/blob/main/turbo.json
- Writing better requirements with EARS - Systems Engineering Trends, accessed July 24, 2025, https://www.se-trends.de/en/requirements-with-ears/
- Monorepos | Nx, accessed July 24, 2025, https://nx.dev/concepts/decisions/why-monorepos
- Getting Started with Nx Monorepos: A Beginner's Guide - Earthly Blog, accessed July 24, 2025, https://earthly.dev/blog/nx-monorepos-guide/
- Learn how to use Nx tools to create Poetry Python monorepos - Better Programming, accessed July 24, 2025, https://betterprogramming.pub/poetry-python-nx-monorepo-5750d8627024
- Using Nx to build a multilang monorepo | Sylhare's blog, accessed July 24, 2025, https://sylhare.github.io/2024/10/21/Nx-multilang-monorepo.html
- Which CMS do you recommend, PayloadCMS or Directus? - LowEndTalk, accessed July 24, 2025, https://lowendtalk.com/discussion/200030/which-cms-do-you-recommend-payloadcms-or-directus
- Nx vs Turborepo: A Comprehensive Guide to Monorepo Tools - Wisp CMS, accessed July 24, 2025, https://www.wisp.blog/blog/nx-vs-turborepo-a-comprehensive-guide-to-monorepo-tools
- Create T3 App, accessed July 24, 2025, https://create.t3.gg/
- juliusmarminge/create-t3-turbo - GitHub, accessed July 24, 2025, https://github.com/juliusmarminge/create-t3-turbo
- better-auth/better-auth: The most comprehensive authentication framework for TypeScript - GitHub, accessed July 24, 2025, https://github.com/better-auth/better-auth
- Better Auth: The authentication framework for TypeScript | Y Combinator, accessed July 24, 2025, https://www.ycombinator.com/companies/better-auth
- Build a User Management App with Next.js | Supabase Docs, accessed July 24, 2025, https://supabase.com/docs/guides/getting-started/tutorials/with-nextjs
- wpcodevo/nextjs-fastapi-framework: In this article, you will learn how to seamlessly integrate a FastAPI project into your Next.js application and deploy the entire project on Vercel. But that's not all! We won't stop at integration; we will take it a step further by building a simple Todo - GitHub, accessed July 24, 2025, https://github.com/wpcodevo/nextjs-fastapi-framework
- Payload: The Next.js Headless CMS and App Framework, accessed July 24, 2025, https://payloadcms.com/
- Detailed Comparison of Payload vs Directus in 2024 - Wisp CMS, accessed July 24, 2025, https://www.wisp.blog/blog/detailed-comparison-of-payload-vs-directus-in-2024
- Compare Payload to Strapi | Strapi Alternatives - Payload CMS, accessed July 24, 2025, https://payloadcms.com/compare/strapi
- Strapi - Open source Node.js Headless CMS, accessed July 24, 2025, https://strapi.io/
- Headless CMS - Top Content Management Systems - Jamstack, accessed July 24, 2025, https://jamstack.org/headless-cms/
- Using TanStack Query with Next.js - LogRocket Blog, accessed July 24, 2025, https://blog.logrocket.com/using-tanstack-query-next-js/
- When to benefit from Tanstack Query when using Next ? : r/nextjs - Reddit, accessed July 24, 2025, https://www.reddit.com/r/nextjs/comments/1iy9l9m/when_to_benefit_from_tanstack_query_when_using/
- TanStack Table, accessed July 24, 2025, https://tanstack.com/table
- Playwright vs Cypress - Detailed comparison [2024] | Checkly, accessed July 24, 2025, https://www.checklyhq.com/learn/playwright/playwright-vs-cypress/
- 5 Best Testing Tools for Next.js - CodeWalnut, accessed July 24, 2025, https://www.codewalnut.com/learn/5-best-testing-tools-for-next-js
- Discussion: Improving Our E2E Test Coverage – Cypress vs. Playwright Migration, accessed July 24, 2025, https://talk.openelis-global.org/t/discussion-improving-our-e2e-test-coverage-cypress-vs-playwright-migration/1098
- Storybook for React Native Web, accessed July 24, 2025, https://storybook.js.org/docs/get-started/frameworks/react-native-web-vite
- Setting up a Storybook with React-Native-Web in a monorepo - Design Systems Collective, accessed July 24, 2025, https://www.designsystemscollective.com/setting-up-a-storybook-with-react-native-web-in-a-monorepo-36c074ce7088
- Adopting EARS Notation for Requirements Specification - Visure Solutions, accessed July 24, 2025, https://visuresolutions.com/alm-guide/adopting-ears-notation/