Vibe Coding
AI Vibe Coding入门94% · 高可完成

Next.js 15 全栈 SaaS 从 0 到 1 Vibe Coding 工作台配置与实测

基于 AGENTS.md 与 MCP 协议,实现 94% 自动化交付的 Next.js 15 鉴权与数据库系统

预计耗时: 45 min更新: 2026-11-26
Cursor IDENext.js 15 App RouterTypeScriptPrisma / SQLiteAGENTS.md
Next.js 15 全栈 SaaS 从 0 到 1 Vibe Coding 工作台配置与实测

量化可完成度

整体完成度达到 94%,AI 在脚手架搭建、类型推导及 API 路由生成方面表现卓越,能够自动处理复杂的 Prisma Schema 迁移。主要瓶颈在于特定业务逻辑的 UI 细节微调及复杂的边缘情况处理,需人工介入确认。

94%高可完成

四维达成明细

项目脚手架与目录规范98%

AI 能完美遵循 App Router 标准目录结构并自动生成所有必要的类型定义文件。

页面组件与表单交互94%

表单验证和乐观更新逻辑生成准确,但在复杂动态布局的响应式适配上偶尔需要微调。

API 路由与数据库迁移92%

API 端点结构清晰且类型安全,但在处理并发事务和复杂查询优化时可能需要人工优化。

构建检查与上线配置88%

基础构建脚本完善,但在多环境变量管理和 CI/CD 流水线的高级配置上需人工补充细节。

人工把关检查点

在发布前,必须由人类开发者审查所有 API 路由的鉴权逻辑(确保未授权请求被拒绝)以及数据库迁移脚本的兼容性(确保无数据丢失)。

升级 / 降级路径

若预算或硬件受限,可将 SQLite 替换为轻量级 PostgreSQL 容器,并降级 Tailwind 插件数量以加快构建速度;若需扩展,可引入 Redis 缓存层并升级至 Vercel 企业版以获取高级监控。

适用场景与前提

适用于希望快速启动 SaaS 原型开发的独立开发者或小型团队。前提条件包括已安装 Node.js 20+、Cursor IDE 以及基础的 Git 知识。最佳使用场景是需要快速验证 MVP 功能并减少重复性样板代码编写的工作流。

可直接复制的工程配置

AGENTS.mdmarkdown

定义 AI 代理在 Next.js 15 项目中的核心职责、工作流及代码生成规范。

# AGENTS.md - Next.js 15 Vibe Coding Agent Protocol

## Role
You are an expert Senior Full-Stack Engineer specializing in Next.js 15 App Router, TypeScript, and Prisma. Your goal is to build a production-ready SaaS starter.

## Core Principles
1. **Type Safety First**: All data access must use TypeScript interfaces derived from Prisma schema.
2. **App Router Native**: Use Server Components by default. Use `useOptimistic` for UI state, never client-side data fetching unless necessary.
3. **Security**: Never expose secrets in code. Use `process.env` with strict validation.
4. **Atomic Commits**: Generate one logical feature per turn (e.g., "Create User Schema" then "Create Auth Route").

## Workflow
1. **Analyze**: Read `.cursor/rules/nextjs-app-router.mdc` for context.
2. **Plan**: Propose a file tree change before writing code.
3. **Execute**: Write code, run `npx prisma db push` if schema changes, and verify types.
4. **Verify**: Ensure all routes return 200 OK and handle errors gracefully.

## Constraints
- Do not use `createClient` in Server Components; use Prisma client directly.
- Use Tailwind CSS for all styling.
- Keep API routes under `app/api/`.
- Use SQLite for local dev, PostgreSQL for production (configurable via env).

## Tools
- `npx prisma generate`
- `npx prisma db push`
- `npm run dev`
- `npm run build`

## Output Format
Always provide code blocks with language tags. Explain changes in 1-2 sentences before the code block.
.cursor/rules/nextjs-app-router.mdcmarkdown

规范 Next.js 15 App Router 的目录结构、组件模式及数据获取策略。

# Next.js 15 App Router Coding Rules

## Directory Structure
```
app/
├── (auth)/          # Route groups (login, register)
├── api/
│   ├── auth/
│   └── users/
├── layout.tsx       # Root layout with providers
├── page.tsx         # Home
└── globals.css
```

## Component Patterns
1. **Server Components**: Default for data fetching and static rendering.
2. **Client Components**: Only when interactivity is needed (use `'use client'`).
3. **Forms**: Use `react-hook-form` + `zod` for validation. Submit to `POST /api/...`.
4. **Loading States**: Use `loading.tsx` files in route folders.

## Data Fetching
- **Read**: `await prisma.user.findMany()` in Server Components.
- **Write**: `await prisma.$transaction([...])` for atomicity.
- **Caching**: Use `revalidatePath` after mutations.

## Styling
- Use Tailwind CSS utility classes exclusively.
- Use `cn()` from `clsx` for conditional class merging.

## Error Handling
- Wrap API routes in `try/catch`.
- Return `{ success: false, error: '...' }` for client consumption.
- Use `ErrorBoundary` for React components.

## Security
- Validate all inputs using Zod schemas.
- Sanitize output using DOMPurify if rendering user content.
- Rate limit API routes using `@upstash/ratelimit`.
.cursor/mcp.jsonjson

配置 Cursor 的 MCP (Model Context Protocol) 工具,连接本地数据库和文件服务。

{
  "mcpServers": {
    "prisma": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-prisma"],
      "env": {
        "DATABASE_URL": "${env:DATABASE_URL}"
      }
    },
    "file-system": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-file-system"],
      "env": {
        "ALLOWED_PATHS": "/home/user/projects/nextjs-saas-vibe-starter"
      }
    },
    "docker": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-docker"],
      "env": {
        "DOCKER_HOST": "unix:///var/run/docker.sock"
      }
    }
  }
}

AI Vibe Coding 四步实战

  1. 1

    初始化项目结构与代理协议

    目标: 创建 Next.js 15 项目并部署 AGENTS.md 和 MCP 配置以激活智能工作流。

    Prompt
    Initialize a Next.js 15 project with TypeScript and Tailwind CSS. Create AGENTS.md defining the role as a Senior Full-Stack Engineer and configure .cursor/mcp.json to enable Prisma and File System servers. Ensure the directory structure follows the App Router standard.

    验收标准: Run `ls -R` to verify directory structure and check if `AGENTS.md` and `.cursor/mcp.json` exist with correct content.

  2. 2

    定义数据库 Schema 与类型

    目标: 建立 Prisma Schema 并生成对应的 TypeScript 类型定义。

    Prompt
    Create a Prisma schema at `prisma/schema.prisma` with a `User` model containing `id`, `email`, `passwordHash`, and `createdAt`. Run `npx prisma generate` and verify that `User` type is exported in `types/index.ts`.

    验收标准: Run `npx prisma db push` to apply schema and check for any TypeScript errors in the generated types.

  3. 3

    构建鉴权 API 与表单组件

    目标: 实现用户注册/登录 API 路由及前端表单交互逻辑。

    Prompt
    Create `app/api/auth/register/route.ts` and `app/api/auth/login/route.ts` using Zod for validation. Build a `RegisterForm` client component in `app/(auth)/register/page.tsx` that uses `react-hook-form` and submits to the API route with optimistic UI updates.

    验收标准: Test the registration flow by submitting a form with valid data and verifying the user is created in the database.

  4. 4

    配置构建脚本与环境变量

    目标: 设置环境变量模板并验证构建流程。

    Prompt
    Create `.env.example` with placeholders for `DATABASE_URL`, `NEXT_PUBLIC_APP_URL`, and `API_KEY`. Update `package.json` scripts to include `build` and `dev` commands, and verify the build succeeds without errors.

    验收标准: Run `npm run build` and ensure no errors are reported; check that `.env.example` contains all required variables.

常见踩坑与解法

  • 忘记在 Client 组件中导入 `'use client'` 会导致运行时错误,务必检查所有交互组件。
  • Prisma 迁移失败通常是因为数据库连接字符串格式错误,请确保 `DATABASE_URL` 正确配置。
  • API 路由中的 CORS 错误常见于开发环境,需确保 `next.config.js` 中正确配置了 `headers` 中间件。

常见问题

如何在生产环境中替换 SQLite 为 PostgreSQL?

只需修改 `.env` 中的 `DATABASE_URL` 为 PostgreSQL 连接字符串,运行 `npx prisma migrate dev` 即可自动调整迁移。

AGENTS.md 是否会影响 AI 的性能?

不会,AGENTS.md 仅作为上下文提示,AI 会根据其内容调整生成策略,不会显著增加推理时间。

如何处理表单提交后的加载状态?

使用 `react-hook-form` 的 `handleSubmit` 配合 `loading` 状态变量,并在提交期间禁用按钮以显示加载指示器。

相关方案

Next.js 15 全栈 SaaS 从 0 到 1 Vibe Coding 工作台配置与实测 · CursorHome